-
Notifications
You must be signed in to change notification settings - Fork 0
/
emails-sender.ts
114 lines (96 loc) · 2.9 KB
/
emails-sender.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
import "./instrument.emails-sender";
import * as Sentry from "@sentry/aws-serverless";
import {
type Callback,
type Context,
type SQSBatchItemFailure,
type SQSBatchResponse,
type SQSEvent,
} from "aws-lambda";
import { CONFIG } from "@/config";
import { TEMPLATES_MAP } from "@/lib/emails/const";
import { isEmailAllowed } from "@/lib/emails/helpers";
import { getJSONFormatHeader, parseRecord } from "@/lib/payload";
import { getEmailProvider } from "@/providers/email";
import { getLogger } from "@/providers/logger";
export const logger = getLogger();
export const handler = Sentry.wrapHandler(
async (
event: SQSEvent,
context: Context,
callback: Callback
): Promise<SQSBatchResponse | void> => {
const batchItemFailures: SQSBatchItemFailure[] = [];
logger.info(`Received event with ${event.Records.length} records.`);
for await (const record of event.Records) {
logger.debug("Processing record", { record });
const {
format,
payload: { data, event },
} = parseRecord(record);
const supportedJSONFormat = getJSONFormatHeader({
version: 1,
name: CONFIG.NAME,
});
if (format === supportedJSONFormat) {
const match = TEMPLATES_MAP[event];
if (!match) {
logger.warn("Received payload with unhandled template.", {
format,
data,
event,
});
continue;
}
const { extractFn, template } = match;
const toEmail = extractFn(data);
const fromEmail = CONFIG.FROM_EMAIL;
const from = CONFIG.FROM_NAME;
if (
!isEmailAllowed({
email: toEmail,
allowedDomains: CONFIG.WHITELISTED_DOMAINS,
})
) {
logger.info("Email domain is not allowed, skipping.", {
toEmail,
event,
allowedDomains: CONFIG.WHITELISTED_DOMAINS,
});
continue;
}
const emailProvider = await getEmailProvider();
const sender = emailProvider({
fromEmail,
from,
toEmail,
logger,
});
logger.debug("Sending email.", { data, fromEmail, from, toEmail });
const html = await sender.render({
props: { data },
template,
});
await sender.send({
html,
subject: template.getSubject(data),
});
logger.info("Email sent successfully.", { toEmail, event });
} else {
logger.warn("Received payload with unsupported format.", {
format,
data,
event,
});
continue;
}
}
if (batchItemFailures.length) {
const failedMessagesId = batchItemFailures.map(
({ itemIdentifier }) => itemIdentifier
);
logger.error(`Failed messages: ${failedMessagesId.join(", ")}.`);
return { batchItemFailures };
}
}
);