|
| 1 | +import { Resend } from "resend"; |
| 2 | +import { actor, setup } from "rivetkit"; |
| 3 | +import type { CampaignInput, CampaignState } from "./types"; |
| 4 | + |
| 5 | +const DAY_IN_MS = 86_400_000; |
| 6 | + |
| 7 | +const EMAIL_SUBJECT = "Daily campaign update"; |
| 8 | +const EMAIL_BODY = [ |
| 9 | + "<p>Hi there,</p>", |
| 10 | + "<p>This is your automated daily campaign email from RivetKit.</p>", |
| 11 | + "<p>Have a great day!</p>", |
| 12 | +].join(""); |
| 13 | + |
| 14 | +const emailCampaignUser = actor({ |
| 15 | + createState: (_c, input: CampaignInput): CampaignState => ({ |
| 16 | + email: input.email, |
| 17 | + }), |
| 18 | + |
| 19 | + onCreate: async (c) => { |
| 20 | + const nextSendAt = Date.now() + DAY_IN_MS; |
| 21 | + c.state.nextSendAt = nextSendAt; |
| 22 | + await c.schedule.at(nextSendAt, "sendDailyEmail"); |
| 23 | + }, |
| 24 | + |
| 25 | + actions: { |
| 26 | + sendDailyEmail: async (c) => { |
| 27 | + const resend = new Resend(process.env.RESEND_API_KEY ?? ""); |
| 28 | + |
| 29 | + const { data, error } = await resend.emails.send({ |
| 30 | + from: process.env.RESEND_FROM_EMAIL ?? "", |
| 31 | + to: c.state.email, |
| 32 | + subject: EMAIL_SUBJECT, |
| 33 | + html: EMAIL_BODY, |
| 34 | + }); |
| 35 | + |
| 36 | + c.state.lastSentAt = Date.now(); |
| 37 | + c.state.lastMessageId = data?.id ?? String(error ?? ""); |
| 38 | + |
| 39 | + const nextSendAt = Date.now() + DAY_IN_MS; |
| 40 | + c.state.nextSendAt = nextSendAt; |
| 41 | + await c.schedule.at(nextSendAt, "sendDailyEmail"); |
| 42 | + }, |
| 43 | + |
| 44 | + getStatus: (c) => c.state, |
| 45 | + }, |
| 46 | +}); |
| 47 | + |
| 48 | +export const registry = setup({ |
| 49 | + use: { emailCampaignUser }, |
| 50 | +}); |
| 51 | + |
| 52 | +export type Registry = typeof registry; |
0 commit comments