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

Tạo Ứng Dụng Newsletter Có Khả Năng Mở Rộng Sử Dụng Upstash Redis Và Workflow

Trong blog này, chúng ta sẽ xây dựng một ứng dụng newsletter nơi người dùng có thể đăng ký và chọn tần suất nhận newsletter. Chúng ta sẽ sử dụng Upstash Redis để lưu trữ dữ liệu đăng ký và Upstash Workflow để quản lý các hành động lưu trữ dữ liệu, gửi email chào mừng, và lên lịch newsletter dựa trên tùy chọn của người dùng.

Động Lực

Thứ nhất, môi trường serverless tuyệt vời! Chúng có khả năng mở rộng cao và dễ dàng cho ngân sách. Tuy nhiên, chúng đi kèm với những hạn chế nhất định, như giới hạn thời gian thực thi. Điều này có thể đặc biệt gây vấn đề khi bạn cần chạy các tác vụ chạy dài.

Đó là nơi Upstash Workflow xuất hiện. Với Upstash Workflow, bạn có thể tạo các workflow bền bỉ có thể chạy selama bao lâu cần thiết. Vì vậy, bạn không phải lo lắng về timeout của serverless function nữa.

Dưới đây là danh sách các tính năng bạn nhận được khi sử dụng Upstash Workflow:

  • Không còn timeout serverless function: Workflow của bạn có thể chạy bao lâu cần thiết.
  • Khôi phục tự động: Nếu có sự cố và workflow thất bại ở giữa, nó tự động khôi phục.
  • Thử lại tự động: Nếu bất kỳ bước nào trong workflow thất bại, nó sẽ được thử lại tự động.
  • Giám sát thời gian thực: Bạn có thể giám sát workflow của mình theo thời gian thực từ Bảng điều khiển Upstash.

Điều Kiện Tiên Quyết

  • Hiểu cơ bản về ứng dụng Next.js.
  • Tài khoản Upstash cho Redis và QStash tokens.
  • Tài khoản Vercel để triển khai.
  • ngrok (khuyến nghị) cho phát triển cục bộ.

Thiết Lập Dự Án

Hãy bắt đầu bằng cách khởi tạo dự án Next.js mới sử dụng create-next-app:

npx create-next-app@latest --typescript newsletter-app cd newsletter-app

Bây giờ, hãy thêm các phụ thuộc cần thiết để tương tác với dịch vụ Upstash QStash và Redis:

npm install @upstash/qstash @upstash/redis

Cấu Trúc Thư Mục

Trước khi đi sâu vào mã, hãy xem nhanh cách chúng ta sẽ tổ chức dự án:

  • src/app/: Nơi các component và trang chính của ứng dụng sẽ nằm.
  • src/app/api/: Chúng ta sẽ đặt API routes ở đây—để đăng ký, hủy đăng ký, và xử lý workflow.
  • src/components/: Thư mục này sẽ chứa component form đăng ký và hủy đăng ký.
  • src/lib/: Các hàm tiện ích cho Redis và gửi email sẽ ở đây.
  • src/types/: Chúng ta sẽ giữ các định nghĩa kiểu TypeScript trong thư mục này.

Biến Môi Trường

Chúng ta cần tạo tệp .env tại thư mục gốc dự án và thêm các nội dung sau:

QSTASH_TOKEN= UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= EMAIL_SERVICE_URL= NEXT_PUBLIC_BASE_URL=
  • QSTASH_TOKEN: Token Upstash QStash được truy cập từ Bảng điều khiển Upstash.
  • UPSTASH_REDIS_REST_URL và UPSTASH_REDIS_REST_TOKEN: Thông tin đăng nhập Upstash Redis được truy cập từ Bảng điều khiển Upstash.
  • EMAIL_SERVICE_URL: Endpoint của API gửi email của chúng ta.
  • NEXT_PUBLIC_BASE_URL: URL cơ sở của ứng dụng đã triển khai (ví dụ: https://your-app.vercel.app).

Chúng ta cũng có thể đặt biến UPSTASH_WORKFLOW_URL trong tệp .env cho phát triển cục bộ với URL ngrok. Để tìm hiểu thêm về cách phát triển workflow cục bộ với ngrok, tham khảo Tài liệu Upstash.

Biến môi trường UPSTASH_WORKFLOW_URL chỉ cần thiết cho phát triển cục bộ. Trong sản xuất, tham số baseUrl được thiết lập tự động và có thể bỏ qua.

Triển Khai Dự Án

Component Form Đăng Ký

Component SubscriptionForm cho phép người dùng nhập email và chọn tần suất họ muốn nhận newsletter. Khi form được gửi, chúng ta gửi request POST đến /api/subscribe với dữ liệu form.

src/components/SubscriptionForm.tsx

"use client"; import React, { useState } from "react"; export default function SubscriptionForm() { const [frequency, setFrequency] = useState("daily"); const [showCustomFrequency, setShowCustomFrequency] = useState(false); const [message, setMessage] = useState(""); const [isError, setIsError] = useState(false); // Handle frequency selection const handleFrequencyChange = (e: React.ChangeEvent<HTMLSelectElement>) => { const value = e.target.value; setFrequency(value); setShowCustomFrequency(value === "custom"); }; // Handle form submission const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); setMessage(""); setIsError(false); const formData = new FormData(e.currentTarget); try { const response = await fetch("/api/subscribe", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(Object.fromEntries(formData.entries())), }); const result = await response.json(); if (!response.ok) { setIsError(true); setMessage(result.error || "An error occurred during subscription."); } else { setIsError(false); setMessage(result.message || "Subscription successful!"); } } catch (error) { console.error("An unexpected error occurred:", error); setIsError(true); setMessage("An unexpected error occurred."); } }; // Render the form return ( <form className="flex flex-col gap-4 text-gray-700" onSubmit={handleSubmit}> <input type="email" name="email" placeholder="Your Email" required className="border p-2 rounded" /> <select name="frequency" value={frequency} onChange={handleFrequencyChange} required className="border p-2 rounded text-gray-700" > <option value="daily">Daily</option> <option value="weekly">Weekly</option> <option value="monthly">Monthly</option> <option value="custom">Custom Amount of Days</option> </select> {showCustomFrequency && ( <input type="number" name="customFrequency" placeholder="Enter number of days" min="1" className="border p-2 rounded text-gray-700" required /> )} <button type="submit" className="bg-blue-500 text-white p-2 rounded"> Subscribe </button> {message && ( <p className={`mt-2 ${isError ? "text-red-500" : "text-green-500"}`}> {message} </p> )} </form> ); }

Component Form Hủy Đăng Ký

Component UnsubscribeForm cho phép người dùng nhập email để hủy đăng ký khỏi newsletter. Khi form được gửi, chúng ta gửi request POST đến /api/unsubscribe với dữ liệu email. Nó cũng tự động điền email nếu người dùng nhấp liên kết hủy đăng ký trong email.

src/components/UnsubscribeForm.tsx

"use client"; import { useState, useEffect, Suspense } from "react"; import { useSearchParams } from "next/navigation"; const UnsubscribeForm = () => { const searchParams = useSearchParams(); const [email, setEmail] = useState(""); const [message, setMessage] = useState(""); const [isError, setIsError] = useState(false); // Pre-fill email from query parameter useEffect(() => { const emailParam = searchParams.get("email"); if (emailParam) { setEmail(emailParam); } }, [searchParams]); // Handle form submission const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setMessage(""); setIsError(false); try { const response = await fetch("/api/unsubscribe", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ email }), }); const data = await response.json(); if (response.ok) { setIsError(false); setMessage("You have been unsubscribed successfully."); } else { setIsError(true); setMessage(data.error || "Something went wrong. Please try again."); } } catch (error) { console.error("Error unsubscribing:", error); setIsError(true); setMessage("An unexpected error occurred. Please try again."); } }; // Render the form return ( <form className="flex flex-col gap-4 text-gray-700" onSubmit={handleSubmit}> <input type="email" name="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Your Email" required className="border p-2 rounded" /> <button type="submit" className="bg-red-500 hover:bg-red-700 text-white p-2 rounded" > Unsubscribe </button> {message && ( <p className={`mt-2 ${isError ? "text-red-500" : "text-green-500"}`}> {message} </p> )} </form> ); }; export default function UnsubscribePage() { return ( <Suspense fallback={<div>Loading...</div>}> <UnsubscribeForm /> </Suspense> ); }

Lưu Trữ Dữ Liệu Trong Redis

Chúng ta sẽ dùng Upstash Redis để lưu trữ dữ liệu đăng ký người dùng.

Để dùng Upstash Redis, trước tiên chúng ta cần thiết lập cơ sở dữ liệu Redis trên Upstash Console và lấy REST URL và token. Để biết thêm thông tin, bạn có thể xem Tài liệu Upstash.

redis.ts sẽ chứa client Redis và các hàm helper để tương tác với Redis:

src/lib/redis.ts

import { Redis } from "@upstash/redis"; export const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL!, token: process.env.UPSTASH_REDIS_REST_TOKEN!, }); export async function getUserFrequency(email: string): Promise<number | null> { const data = await redis.get(`user:${email}`); console.log("User data:", data); if (!data) return null; const parsed = JSON.parse(JSON.stringify(data)); return parsed.frequency; } export async function removeUser(email: string): Promise<void> { await redis.del(`user:${email}`); } export async function checkSubscription(email: string): Promise<boolean> { return (await getUserFrequency(email)) !== null; }

Hàm Gửi Email

Để gửi email, chúng ta sẽ dùng API email của chính chúng ta mà chúng ta đã phát triển trong bài blog trước về tạo Email Scheduler với QStash Python SDK.

src/lib/email.ts

export async function sendEmail(message: string, email: string) { console.log(`Sending email to ${email}`); const url = process.env.EMAIL_SERVICE_URL; const payload = { to_email: email, subject: "Upstash Newsletter", content: message, }; if (!url) { console.error("EMAIL_SERVICE_URL is not defined."); return; } const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(payload), }); if (!response.ok) { console.error("Failed to send email:", await response.text()); } }

Định Nghĩa Kiểu

Chúng ta cũng cần định nghĩa kiểu cho dữ liệu đăng ký:

src/types/index.ts

export type SubscriptionData = { email: string; frequency: string; customFrequency?: string; };

API Route Đăng Ký

Chúng ta sẽ tạo API route xử lý yêu cầu đăng ký. Khi người dùng gửi form đăng ký, endpoint này sẽ kiểm tra xem người dùng đã đăng ký chưa và đưa workflow vào hàng đợi để xử lý gửi email dựa trên tần suất người dùng chọn.

src/app/api/subscribe/route.ts

import { NextRequest, NextResponse } from "next/server"; import { checkSubscription } from "@/lib/redis"; export const POST = async (request: NextRequest) => { try { const { email, frequency: freq, customFrequency } = await request.json(); console.log("Email:", email); console.log("Frequency:", freq); console.log("Custom Frequency:", customFrequency); if (!email || !freq) { console.error("Email and frequency are required."); return NextResponse.json( { error: "Email and frequency are required." }, { status: 400 } ); } let frequency = freq; if (frequency === "custom") { if (!customFrequency) { console.error("Custom frequency days are required."); return NextResponse.json( { error: "Custom frequency days are required." }, { status: 400 } ); } frequency = customFrequency; } if (frequency === "daily") { frequency = "1"; } else if (frequency === "weekly") { frequency = "7"; } else if (frequency === "monthly") { frequency = "30"; } const frequencyNumber = Number(frequency); if (isNaN(frequencyNumber) || frequencyNumber <= 0) { console.error("Invalid frequency value."); return NextResponse.json( { error: "Invalid frequency value." }, { status: 400 } ); } const exists = await checkSubscription(email); if (exists) { console.error("Email is already subscribed."); return NextResponse.json( { error: "Email is already subscribed." }, { status: 400 } ); } console.log("Subscription successful!"); console.log("Enqueue the workflow"); // Enqueue the workflow await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/workflow`, { method: "POST", headers: { Authorization: `Bearer ${process.env.QSTASH_TOKEN}`, "Content-Type": "application/json", }, body: JSON.stringify({ email: email, frequency: frequencyNumber, }), }) .then((response) => { if (!response.ok) { console.error("Failed to enqueue workflow:", response.statusText); return NextResponse.json( { error: "Failed to enqueue workflow." }, { status: 500 } ); } else { console.log("Workflow enqueued successfully"); } }) .catch((error) => { console.error("Error enqueuing workflow:", error); return NextResponse.json( { error: "Error enqueuing workflow." }, { status: 500 } ); }); return NextResponse.json({ message: "Subscription successful!" }); } catch (error) { console.error("Error occurred:", error); return NextResponse.json( { error: "An error occurred during subscription." }, { status: 500 } ); } };

API Route Hủy Đăng Ký

Vì chúng ta có route đăng ký, chúng ta cần route hủy đăng ký. Khi có yêu cầu, chúng ta sẽ kiểm tra xem người dùng đã đăng ký và xóa dữ liệu của họ khỏi Redis. Chúng ta cũng sẽ gửi email xác nhận.

src/app/api/unsubscribe/route.ts

import { NextRequest, NextResponse } from "next/server"; import { redis } from "@/lib/redis"; import { sendEmail } from "@/lib/email"; export const POST = async (request: NextRequest) => { try { const { email } = await request.json(); if (!email) { return NextResponse.json( { error: "Email is required." }, { status: 400 } ); } const userExists = await redis.exists(`user:${email}`); if (!userExists) { return NextResponse.json( { error: "Email is not subscribed." }, { status: 400 } ); } // Remove the user from Redis await redis.del(`user:${email}`); // Send an email to confirm unsubscription await sendEmail( "You have been unsubscribed from Upstash Newsletter.", email ); return NextResponse.json({ message: "You have been unsubscribed." }); } catch (error) { console.error("Unsubscribe error:", error); return NextResponse.json( { error: "An error occurred. Please try again." }, { status: 500 } ); } };

API Route Workflow

Bây giờ, đây là phần thú vị! Chúng ta sẽ tạo API route xử lý workflow để gửi newsletter theo khoảng thời gian tần suất được chỉ định.

Workflow của chúng ta sẽ làm như sau:

  1. Lưu dữ liệu đăng ký của người dùng trong Redis.
  2. Gửi email chào mừng.
  3. Vào vòng lặp:
    • Chờ đợi khoảng thời gian tần suất được chỉ định.
    • Kiểm tra xem người dùng vẫn còn đăng ký không.
    • Gửi email newsletter.
    • Lặp lại cho đến khi một số lượng newsletter nhất định đã được gửi vì chúng ta không muốn vòng lặp vô hạn.

src/app/api/workflow/route.ts

Dưới đây là ví dụ về workflow hoàn chỉnh cho người dùng đã đăng ký, nhận một newsletter, và hủy đăng ký:

Tạo Ứng Dụng Newsletter Có Khả Năng Mở Rộng Sử Dụng Upstash Redis Và Workflow

Bạn có thể truy cập và giám sát workflow của mình từ Bảng điều khiển Upstash.

Component Trang Chính

Hãy thiết lập trang chính của ứng dụng. Trang này sẽ bao gồm form đăng ký và liên kết đến trang hủy đăng ký.

src/app/page.tsx

import SubscriptionForm from "@/components/SubscriptionForm"; import Link from "next/link"; export default function Home() { return ( <main className="flex flex-col items-center justify-center min-h-screen p-4"> <h1 className="text-3xl font-bold mb-6"> Subscribe to Upstash Newsletter </h1> {/* Subscription Form */} <SubscriptionForm /> {/* Unsubscribe Link */} <div className="mt-8"> <p className="text-gray-600"> Already subscribed and want to unsubscribe? <Link href="/unsubscribe" className="text-red-500 hover:text-red-700 font-bold ml-2" > Click here to unsubscribe </Link> </p> </div> </main> ); }

Component Trang Hủy Đăng Ký

Cuối cùng, hãy tạo trang hủy đăng ký.

src/app/unsubscribe/page.tsx

import UnsubscribePage from "@/components/UnsubscribeForm"; export default function UnsubscribeHome() { return ( <main className="flex flex-col items-center justify-center min-h-screen p-4"> <h1 className="text-3xl font-bold mb-6"> Unsubscribe from Upstash Newsletter </h1> {/* Unsubscribe Form */} <UnsubscribePage /> </main> ); }

Kết Luận

Và bạn đã có nó! Chúng ta đã xây dựng một ứng dụng newsletter đơn giản mà không lo lắng về timeout serverless function.

Bạn có thể tìm mã nguồn hoàn chỉnh cho dự án này trên GitHub và xem demo trực tiếp tại đây.

Để biết thêm thông tin về Upstash Workflow, bạn có thể tham khảo Tài liệu Upstash.

Nếu bạn có bất kỳ câu hỏi nào, đừng ngần ngại liên hệ với chúng tôi trên Discord. Cũng đừng quên khám phá Blog Upstash để xem thêm hướng dẫn và trường hợp sử dụng.