-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmailListController.ts
More file actions
78 lines (68 loc) · 2.38 KB
/
mailListController.ts
File metadata and controls
78 lines (68 loc) · 2.38 KB
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
import { Request, Response } from "express";
import mailSvc from "../services/mailServices";
import mailUtils from "../utils/mailUtils";
import generateHtml from "../helpers/generateHtml";
const add = async (req: Request, res: Response) => {
const payload = req.body;
const results = await mailSvc.addRecipients(payload);
return res.json({ results });
};
const list = async (req: Request, res: Response) => {
const filter = req.query || {};
const docs = await mailSvc.listRecipients(filter as any);
return res.json(docs);
};
const update = async (req: Request, res: Response) => {
const payload = req.body;
const results = await mailSvc.updateRecipients(payload);
return res.json({ results });
};
const remove = async (req: Request, res: Response) => {
const identifiers = req.body.identifiers || req.query.identifiers;
if (!identifiers) return res.status(400).json({ error: "No identifiers provided" });
const results = await mailSvc.removeRecipients(identifiers);
return res.json({ results });
};
const sendAll = async (req: Request, res: Response) => {
const subject = (req.body && req.body.subject) || "Notification from Simple Mailer";
const text = (req.body && req.body.text) || "";
const recipients = await mailSvc.listRecipients();
const base = (process.env.BASE_URL || ").replace(/\/$/, ");
const messages = recipients.map((r: any) => {
const unsubscribeUrl = `${base}/unsubscribe?uuid=${r.uuid}`;
const html = generateHtml(r.name, unsubscribeUrl);
return {
to: r.email,
subject,
text,
html,
mailingList: {
listId: process.env.MAIL_LIST_ID || "simple-mailer",
unsubscribe: `<${unsubscribeUrl}>`,
oneClickUnsubscribe: true,
autoSubmitted: false,
precedence: "bulk",
},
};
});
// Fire-and-forget: kick off sending asynchronously and return immediately.
mailUtils
.sendMail(messages)
.then((results) => {
// Log summary when finished
// eslint-disable-next-line no-console
console.log('[mailListController] sendAll completed:', results.length, 'messages');
})
.catch((err) => {
// eslint-disable-next-line no-console
console.error('[mailListController] sendAll error:', err);
});
return res.status(202).json({ queued: recipients.length, message: 'Sending started' });
};
export default {
add,
list,
update,
remove,
sendAll,
};