-
Notifications
You must be signed in to change notification settings - Fork 612
/
onTransportBeforeSend.ts
63 lines (57 loc) · 1.94 KB
/
onTransportBeforeSend.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
import WebinyError from "@webiny/error";
import zod from "zod";
import { Topic } from "@webiny/pubsub/types";
import { OnTransportBeforeSendParams } from "~/types";
import { SafeParseReturnType } from "zod/lib/types";
const requiredString = zod.string();
const requiredEmail = requiredString.email();
const schema = zod
.object({
to: zod.array(requiredEmail).optional(),
from: zod.string().email().optional(),
subject: requiredString.max(1024).min(2),
cc: zod.array(requiredEmail).optional(),
bcc: zod.array(requiredEmail).optional(),
replyTo: zod.string().email().optional(),
text: zod.string().optional(),
html: zod.string().optional()
})
.refine(data => {
return !!data.text || !!data.html;
}, "Either text or html is required.");
type SchemaType = zod.infer<typeof schema>;
interface Params {
onTransportBeforeSend: Topic<OnTransportBeforeSendParams>;
}
export const attachOnTransportBeforeSend = (params: Params) => {
const { onTransportBeforeSend } = params;
onTransportBeforeSend.subscribe(async ({ data: input }) => {
let result: SafeParseReturnType<SchemaType, SchemaType>;
try {
result = schema.safeParse(input);
if (result.success) {
return;
}
throw new WebinyError({
message: "Error while validating e-mail params.",
code: "VALIDATION_ERROR",
data: {
error: result.error,
input
}
});
} catch (ex) {
if (ex instanceof WebinyError) {
throw ex;
}
throw new WebinyError({
message: "Error while validating e-mail params.",
code: "VALIDATION_ERROR",
data: {
input,
error: ex
}
});
}
});
};