Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Redis

Gửi Email Alert Chính Xác Khi Bạn Muốn: Lập Lịch Theo Múi Giờ Với QStash

Tại docsly, chúng tôi launch tính năng mới gửi email notification cho user với tóm tắt tất cả feedback nhận được trong tuần hoặc tháng qua. Gửi email không phải vấn đề mới, nhưng chúng tôi muốn cung cấp UX tốt nhất, nên quyết định tất cả email phải gửi theo múi giờ user để tránh gửi email ở giờ lạ. Chúng tôi cũng muốn user chọn frequency nhận email. Và cho user hủy scheduled email notification bất cứ lúc nào.

Triển khai giải pháp này tricky vì:

  1. Không muốn lưu múi giờ user trong database của chúng tôi.
  2. Cũng không muốn chạy cron job mỗi phút/giờ check xem đã đến giờ gửi email.
  3. Cũng muốn user hủy scheduled email notification.

Vì vậy, giải pháp độc đáo: Lập lịch cron job trong múi giờ user, sau đó hủy cron job khi user hủy email notification. Nhưng vẫn còn câu hỏi: làm sao?

Chúng tôi đã dùng Upstash làm Redis store, và thấy QStash hỗ trợ feature Schedules. Khám phá sâu hơn, QStash hỗ trợ CRON expression. Vậy quyết định dùng QStash lên lịch cron job.

Bài viết hướng dẫn quy trình lên lịch email trong múi giờ user dùng QStash và Upstash Redis trong Next.js app. Complete source code trên GitHub.

Xây Dựng Next.js App Lên Lịch Email Theo Múi Giờ User

Yêu Cầu Tiên Quyết

Follow tutorial cần:

  • Tài khoản Upstash
  • Môi trường phát triển Node.js

Thiết Lập Dự Án

Bắt đầu, tạo Next.js project mới:

npx create-next-app qstash-email-scheduling

Cài dependencies tương tác Upstash:

npm install --save @upstash/redis axios

Tạo file .env.local ở root project thêm biến môi trường từ tài khoản Upstash:

UPSTASH_REDIS_REST_URL=
UPSTASH_REDIS_REST_TOKEN=
QSTASH_URL=
QSTASH_TOKEN=
QSATSH_CURRENT_SIGNING_KEY=
QSATSH_NEXT_SIGNING_KEY=

Tổng Quan Giải Pháp

Trước khi implement code, xem tổng quan giải pháp. Tạo ba Next.js API routes:

  • POST /api/schedule-cron - lên lịch email cron job trong múi giờ user.
  • POST /api/cancel-schedule - hủy scheduled email cron job.
  • POST /api/send-email - triggered bởi scheduled cron job gửi email.

Ngoài API routes, tạo form đơn giản thu thập thời gian ưu tiên user nhận email.

Tạo User Interface

Tạo page mới app/page.tsx với code:

"use client";
import { useState } from "react";
import axios from "axios";
export default function Home() {
  const userId = "tony-stark-11";
  const [selectedTime, setSelectedTime] = useState("10:00");
  async function createEmailNotificationSchedule() {
    try {
      await axios.post(
        "/api/schedule-cron",
        { userId, selectedTime, utcOffset: new Date().getTimezoneOffset() },
        { headers: { "Content-Type": "application/json" } },
      );
      alert("Email notification scheduled");
    } catch (e) {
      console.log("Client side error", e);
      alert("Error scheduling email notification");
    }
  }
  async function cancelEmailNotificationSchedule() {
    try {
      await axios.post(
        "/api/cancel-schedule",
        { userId },
        { headers: { "Content-Type": "application/json" } },
      );
      alert("Email notification schedule cancelled");
    } catch (e) {
      console.log("Client side error", e);
      alert("Error scheduling email notification");
    }
  }
  return (
    <main className="mx-auto flex min-h-screen max-w-md flex-col justify-center p-24">
      <h1 className="mb-4 text-xl font-bold text-neutral-600">
        Email Notification for {userId}
      </h1>
      Send daily email summary at:
      <select onChange={(e) => setSelectedTime(e.target.value)} className="mt-4 h-12 w-64 rounded-lg border-2 border-neutral-600 bg-neutral-800 p-2 text-white">
        {new Array(24).fill(0).map((_, i) => {
          const time = i < 10 ? `0${i}:00` : `${i}:00`;
          return (
            <option key={i} value={time}>
              {time}
            </option>
          );
        })}
      </select>
      <button className="mt-4 rounded bg-green-700 px-4 py-2 text-white" onClick={createEmailNotificationSchedule}>
        Schedule
      </button>
      <button className="mt-4 rounded bg-red-500 px-4 py-2 text-white" onClick={cancelEmailNotificationSchedule}>
        Cancel Schedule
      </button>
    </main>
  );
}

Code trên tạo form dropdown user set thời gian ưu tiên nhận daily email summary. User schedule hoặc cancel notification, app giao tiếp server qua HTTP POST. Tạo HTTP endpoints ở phần sau.

Gửi Email Alert Chính Xác Khi Bạn Muốn: Lập Lịch Theo Múi Giờ Với QStash

Lên Lịch Email Cron Job

Gửi Email Alert Chính Xác Khi Bạn Muốn: Lập Lịch Theo Múi Giờ Với QStash

Bắt đầu tạo route POST /api/schedule-cron. Route này lên lịch email cron job trong múi giờ user. Dùng QStash library lên lịch cron job.

import { NextApiRequest, NextApiResponse } from "next";
import { Redis } from "@upstash/redis";
import axios from "axios";
export const QSTASH_CONFIG = {
  QSTASH_URL: process.env.QSTASH_URL,
  QSTASH_TOKEN: process.env.QSTASH_TOKEN,
  QSTASH_CURRENT_SIGNING_KEY: process.env.QSTASH_CURRENT_SIGNING_KEY,
};
export const upstash = new Redis({
  url: process.env.UPSTASH_REDIS_REST_URL!,
  token: process.env.UPSTASH_REDIS_REST_TOKEN!,
});
// Edit endpoint này match domain bạn
const SUMMARY_ENDPOINT = "https://<your-domain>/api/send-email";
export default async function scheduleSummary(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  console.log("========SCHEDULE SUMMARY========");
  if (req.method !== "POST") {
    return res.status(400).json({ message: "bad request" });
  }
  const { body } = req;
  const { userId, selectedTime, utcOffset } = body;
  const emailScheduleKey = `email-schedule-${userId}`;
  const scheduleId = await upstash.get(emailScheduleKey);
  // xóa schedule hiện có trước khi tạo mới
  if (scheduleId) {
    try {
      await axios.delete(
        `https://qstash.upstash.io/v1/schedules/${scheduleId}`,
        {
          headers: {
            Authorization: `Bearer ${QSTASH_CONFIG.QSTASH_TOKEN}`,
          },
        },
      );
    } catch (e) {
      console.log("Schedule not found in QStash ");
    }
    await upstash.del(emailScheduleKey);
  }
  const [hour, min] = convertToUTC(selectedTime, utcOffset).split(":");
  const selectedCron = `${min} ${hour} * * *`;
  // tạo và lưu schedule mới
  try {
    const { data, status } = await axios.post(
      `${QSTASH_CONFIG.QSTASH_URL}${SUMMARY_ENDPOINT}`,
      { userId },
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${QSTASH_CONFIG.QSTASH_TOKEN}`,
          "Upstash-Cron": selectedCron,
        },
      },
    );
    console.log({ data, status });
    if (data.scheduleId) {
      await upstash.set(emailScheduleKey, data.scheduleId);
    }
  } catch (e) {
    console.log({ e });
  }
  return res.status(200).json({ message: "success" });
}
function convertToUTC(timeString: string, utcOffset: number) {
  const [hours, minutes] = timeString.split(":").map(Number);
  const timeInMinutes = hours * 60 + minutes;
  const utcTimeInMinutes = (timeInMinutes + utcOffset + 1440) % 1440;
  const utcHours = Math.floor(utcTimeInMinutes / 60);
  const utcMinutes = utcTimeInMinutes % 60;
  return `${utcHours.toString().padStart(2, "0")}:${utcMinutes
    .toString()
    .padStart(2, "0")}`;
}

Core của code là function scheduleSummary, API endpoint. Xử lý POST request đến thực hiện các bước:

  1. Validate request method, đảm bảo là POST.
  2. Extract data từ request body: userId, selectedTime, utcOffset.
  3. Tạo key cho email schedule user trong database Upstash.
  4. Lấy schedule hiện có của user và xóa khỏi QStash.
  5. Chuyển thời gian user chọn sang UTC format dùng function convertToUTC nhận time string và UTC offset, chuyển sang UTC format tính đến offset.
  6. Tạo schedule mới gửi email summary dùng QStash scheduling, thêm userId làm payload endpoint /api/send-email nhận.
  7. Lưu schedule ID mới tạo vào database Upstash.

Gửi Email Summary

Route POST /api/send-email triggered bởi scheduled cron job gửi email. Dùng library @upstash/qstash/nextjs verify chữ ký request. Đảm bảo request từ QStash không phải nguồn khác.

Function POST /api/send-email nhận userId trong request body. Bạn implement function chuẩn bị và gửi email dựa trên userId.

import { NextApiRequest, NextApiResponse } from "next";
import { verifySignature } from "@upstash/qstash/nextjs";
async function handler(request: NextApiRequest, res: NextApiResponse) {
  console.log("==========Project summary handler==========");
  if (request.method !== "POST") {
    return res.status(400).json({ message: "bad request" });
  }
  const { body } = request;
  const { userId } = body;
  // chuẩn bị và gửi email
  return res.status(200).json({ message: "success" });
}
export default verifySignature(handler);
export const config = {
  api: {
    bodyParser: false,
  },
};

Hủy Scheduled Email Cron Job

Gửi Email Alert Chính Xác Khi Bạn Muốn: Lập Lịch Theo Múi Giờ Với QStash

Tiếp, tạo route POST /api/cancel-schedule. Route này hủy scheduled email cron job. Dùng QStash library hủy cron job.

import { NextApiRequest, NextApiResponse } from "next";
import axios from "axios";
import { Redis } from "@upstash/redis";
export const QSTASH_CONFIG = {
  QSTASH_URL: process.env.QSTASH_URL,
  QSTASH_TOKEN: process.env.QSTASH_TOKEN,
  QSTASH_CURRENT_SIGNING_KEY: process.env.QSTASH_CURRENT_SIGNING_KEY,
};
export const upstash = new Redis({
  url: process.env.UPSTASH_REDIS_REST_URL!,
  token: process.env.UPSTASH_REDIS_REST_TOKEN!,
});
export default async function scheduleSummary(
  req: NextApiRequest,
  res: NextApiResponse
) {
  console.log("========REMOVE SCHEDULE SUMMARY========");
  if (req.method !== "POST") {
    return res.status(400).json({ message: "bad request" });
  }
  const { body } = req;
  const { userId } = body;
  const emailScheduleKey = `email-schedule-${userId}`;
  const scheduleId = await upstash.get(emailScheduleKey);
  // xóa schedule hiện có trước khi tạo mới
  if (scheduleId) {
    try {
      await axios.delete(
        `https://qstash.upstash.io/v1/schedules/${scheduleId}`,
        {
          headers: {
            Authorization: `Bearer ${QSTASH_CONFIG.QSTASH_TOKEN}`,
          },
        }
      );
    } catch (e) {
      console.log("Schedule not found in QStash ");
    }
    await upstash.del(emailScheduleKey);
  }
  return res.status(200).json({ message: "success" });
}

Kết Luận

Tóm lại, chúng tôi lên lịch email trong múi giờ user dùng Upstash Redis và QStash. Đạt được điều này không lưu múi giờ user trong database. Cũng cho user hủy scheduled email notification bất cứ lúc nào.

Nếu bạn maintain documentation cho sản phẩm, check out docsly. Công cụ feedback cho technical documentation giúp thu thập feedback từ user biến thành actionable insights.