-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.ts
More file actions
87 lines (73 loc) · 2.28 KB
/
handler.ts
File metadata and controls
87 lines (73 loc) · 2.28 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
79
80
81
82
83
84
85
86
87
import type { FunctionContext, FunctionHandler } from '@constructive-io/fn-runtime';
import { send as sendSmtp } from 'simple-smtp-server';
import { send as sendPostmaster } from '@constructive-io/postmaster';
import { parseEnvBoolean } from '@pgpmjs/env';
import { createLogger } from '@pgpmjs/logger';
type SimpleEmailPayload = {
to: string;
subject: string;
html?: string;
text?: string;
from?: string;
replyTo?: string;
};
const isNonEmptyString = (value: unknown): value is string =>
typeof value === 'string' && value.trim().length > 0;
const getRequiredField = (
payload: SimpleEmailPayload,
field: keyof SimpleEmailPayload
) => {
const value = payload[field];
if (!isNonEmptyString(value)) {
throw new Error(`Missing required field '${String(field)}'`);
}
return value;
};
const isDryRun = parseEnvBoolean(process.env.SIMPLE_EMAIL_DRY_RUN) ?? false;
const useSmtp = parseEnvBoolean(process.env.EMAIL_SEND_USE_SMTP) ?? false;
const logger = createLogger('simple-email');
const handler: FunctionHandler<SimpleEmailPayload> = async (
params: SimpleEmailPayload,
_context: FunctionContext
) => {
const to = getRequiredField(params, 'to');
const subject = getRequiredField(params, 'subject');
const html = isNonEmptyString(params.html) ? params.html : undefined;
const text = isNonEmptyString(params.text) ? params.text : undefined;
if (!html && !text) {
throw new Error("Either 'html' or 'text' must be provided");
}
const fromEnv = useSmtp ? process.env.SMTP_FROM : process.env.MAILGUN_FROM;
const from = isNonEmptyString(params.from)
? params.from
: isNonEmptyString(fromEnv)
? fromEnv
: undefined;
const replyTo = isNonEmptyString(params.replyTo)
? params.replyTo
: undefined;
const logContext = {
to,
subject,
from,
replyTo,
hasHtml: Boolean(html),
hasText: Boolean(text)
};
if (isDryRun) {
logger.info('DRY RUN email (no send)', logContext);
} else {
const sendEmail = useSmtp ? sendSmtp : sendPostmaster;
await sendEmail({
to,
subject,
...(html && { html }),
...(text && { text }),
...(from && { from }),
...(replyTo && { replyTo })
});
logger.info('Sent email', logContext);
}
return { complete: true };
};
export default handler;