-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlerPost.ts
276 lines (247 loc) · 7.02 KB
/
handlerPost.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import { Resend } from "npm:resend";
import * as Sentry from "https://deno.land/x/sentry@8.27.0/index.mjs";
import { renderEmailEvent_5_2025_01_29 } from "https://raw.githubusercontent.com/nn1-dev/emails/main/emails/event-5-2025-01-29.tsx";
import { renderEmailNewsletter_2025_01_16 } from "https://raw.githubusercontent.com/nn1-dev/emails/main/emails/newsletter-2025-01-16.tsx";
import { renderEmailNewsletter_2025_02_03 } from "https://raw.githubusercontent.com/nn1-dev/emails/main/emails/newsletter-2025-02-03.tsx";
import { chunkArray } from "./utils.ts";
const resend = new Resend(Deno.env.get("API_KEY_RESEND"));
// https://resend.com/docs/api-reference/emails/send-batch-emails
const RESEND_MAX_BATCH_CHUNK = 100;
const TEMPLATE_MAPPER_NEWSLETTER: Record<
string,
{
template: (props: { unsubscribeUrl: string }) => Promise<{
html: string;
text: string;
}>;
subject: string;
}
> = {
"2025-01-16": {
template: renderEmailNewsletter_2025_01_16,
subject:
"NN1 Dev Club #5: Hack & Share - a rundown of side projects by Northamptonshire geeks",
},
"2025-02-03": {
template: renderEmailNewsletter_2025_02_03,
subject:
'NN1 Dev Club #6: "Move Fast and Build Things: A Non-Technical Guide to AI Agents" by Eric Bye and "Dark Side of the Moon" by Rehan Butt',
},
};
const TEMPLATE_MAPPER_EVENT: Record<
string,
{
template: (props: { ticketUrl: string }) => Promise<{
html: string;
text: string;
}>;
subject: string;
}
> = {
"5-2025-01-29": {
template: renderEmailEvent_5_2025_01_29,
subject: "NN1 Dev Club #5 - See you tomorrow 👋",
},
};
const fetchMembersEvent = async (eventId: number) => {
try {
const response = await fetch(`https://tickets.nn1.dev/${eventId}`, {
headers: {
Authorization: `Bearer ${Deno.env.get("API_KEY_TICKETS")}`,
},
});
const responseJson: {
data: {
key: ["nn1-dev-tickets", number, string];
value: {
timestamp: string;
eventId: number;
name: string;
email: string;
confirmed: boolean;
};
versionstamp: string;
}[];
} = await response.json();
return responseJson.data.filter((member) => member.value.confirmed);
} catch {
Sentry.captureException(new Error("Failed to fetch event members."));
return [];
}
};
const fetchMembersNewsletter = async () => {
try {
const response = await fetch(`https://newsletter.nn1.dev`, {
headers: {
Authorization: `Bearer ${Deno.env.get("API_KEY_NEWSLETTER")}`,
},
});
const responseJson: {
data: {
key: ["nn1-dev-newsletter", string];
value: {
timestamp: string;
email: string;
};
versionstamp: string;
}[];
} = await response.json();
return responseJson.data;
} catch {
Sentry.captureException(new Error("Failed to fetch newsletter members."));
return [];
}
};
type BodyNewsletter = {
template: keyof typeof TEMPLATE_MAPPER_NEWSLETTER;
audience: "newsletter";
excludeMembersEventId?: number;
};
type BodyEvent = {
template: keyof typeof TEMPLATE_MAPPER_EVENT;
audience: "event";
eventId: number;
};
const isBroadcastAudienceNewsletter = (
body: BodyNewsletter | BodyEvent,
): body is BodyNewsletter => body.audience === "newsletter";
async function createEmailPayload(
{ to, subject, templatePromise }: {
to: string;
subject: string;
templatePromise: () => Promise<{
html: string;
text: string;
}>;
},
) {
const { html, text } = await templatePromise();
return {
from: "NN1 Dev Club <club@nn1.dev>",
to,
subject,
html,
text,
};
}
const handlerPost = async (request: Request) => {
const body: BodyNewsletter | BodyEvent = await request.json();
const shouldBroadcastNewsletter = isBroadcastAudienceNewsletter(body);
if (
!Object.keys(
shouldBroadcastNewsletter
? TEMPLATE_MAPPER_NEWSLETTER
: TEMPLATE_MAPPER_EVENT,
).includes(body.template)
) {
return Response.json(
{
status: "error",
statusCode: 400,
data: null,
error: "Template is not configured",
},
{ status: 400 },
);
}
const data: string[] = [];
if (shouldBroadcastNewsletter) {
const template = TEMPLATE_MAPPER_NEWSLETTER[
body.template as keyof typeof TEMPLATE_MAPPER_NEWSLETTER
];
const membersNewsletter = await fetchMembersNewsletter();
const membersExcluded = body.excludeMembersEventId
? await fetchMembersEvent(body.excludeMembersEventId)
: [];
const entries = membersNewsletter.filter(
(memberNewsletter) =>
!membersExcluded.some(
(memberEvent) =>
memberEvent.value.email === memberNewsletter.value.email,
),
);
const payloads = await Promise.all(
entries.map((entry) =>
createEmailPayload(
{
to: entry.value.email,
subject: template.subject,
templatePromise: () =>
template.template({
unsubscribeUrl: `https://nn1.dev/newsletter/unsubscribe/${
entry?.key[1]
}`,
}),
},
)
),
);
const payloadsChunked = chunkArray(payloads, RESEND_MAX_BATCH_CHUNK);
try {
for (const chunk of payloadsChunked) {
await resend.batch.send(chunk);
}
} catch {
Sentry.captureException(new Error("Emails scheduling failed."));
return Response.json(
{
status: "error",
statusCode: 500,
data: null,
error: "Failed to schedule an email.",
},
{ status: 500 },
);
}
data.push(...entries.map((item) => item.value.email));
} else {
const template = TEMPLATE_MAPPER_EVENT[
body.template as keyof typeof TEMPLATE_MAPPER_EVENT
];
const entries = await fetchMembersEvent(body.eventId);
const payloads = await Promise.all(
entries.map((entry) =>
createEmailPayload(
{
to: entry.value.email,
subject: template.subject,
templatePromise: () =>
template.template({
ticketUrl: `https://nn1.dev/events/${entry.key[1]}/${
entry.key[2]
}`,
}),
},
)
),
);
const payloadsChunked = chunkArray(payloads, RESEND_MAX_BATCH_CHUNK);
try {
for (const chunk of payloadsChunked) {
await resend.batch.send(chunk);
}
} catch {
Sentry.captureException(new Error("Emails scheduling failed."));
return Response.json(
{
status: "error",
statusCode: 500,
data: null,
error: "Failed to schedule an email.",
},
{ status: 500 },
);
}
data.push(...entries.map((item) => item.value.email));
}
return Response.json(
{
status: "success",
statusCode: 200,
data,
error: null,
},
{ status: 200 },
);
};
export default handlerPost;