1 | module.exports = ({
|
2 | Email,
|
3 | Entity,
|
4 | router,
|
5 | asyncMiddleware,
|
6 | getConfig,
|
7 | handleResponse,
|
8 | handleError,
|
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 | router.all(
|
47 | '/email/template.:ext?',
|
48 | asyncMiddleware(async (req, res) => {
|
49 | const input = Object.keys(req.body).length ? req.body : req.query || {};
|
50 |
|
51 | const options = {
|
52 | data: input.data ? JSON.parse(input.data) : false,
|
53 | preview: input.preview ? JSON.parse(input.preview) : false,
|
54 | inky: input.inky ? JSON.parse(input.inky) : false,
|
55 | mjml: input.mjml ? JSON.parse(input.mjml) : false,
|
56 | skipValidation: input.skipValidation ? JSON.parse(input.skipValidation) : false,
|
57 | };
|
58 |
|
59 | const slug = req.session.slug || input.slug;
|
60 |
|
61 | if (!slug) {
|
62 | throw new Error('missing slug param');
|
63 | }
|
64 |
|
65 | async function renderTemplate(data = {}) {
|
66 | if (options.data) {
|
67 | handleResponse(req, res, data);
|
68 | return;
|
69 | }
|
70 |
|
71 | const email = Email(await getConfig(slug));
|
72 |
|
73 | const template = await email.getTemplate(`${slug}/${input.templateSlug}`, data, options);
|
74 |
|
75 | try {
|
76 | handleResponse(req, res, template.html);
|
77 | } catch (error) {
|
78 | handleError(req, res, error);
|
79 | }
|
80 | }
|
81 |
|
82 | if (input.payload) {
|
83 | renderTemplate(JSON.parse(input.payload));
|
84 | return;
|
85 | }
|
86 |
|
87 | if (input.entityId) {
|
88 | const entity = Entity(await getConfig(slug));
|
89 |
|
90 | entity.entitiesById([input.entityId], true, false, true)
|
91 | .then((entities) => {
|
92 | entities = entity.flattenValues(entities);
|
93 |
|
94 | renderTemplate(entities[0]);
|
95 | });
|
96 |
|
97 | return;
|
98 | }
|
99 |
|
100 | renderTemplate();
|
101 | })
|
102 | );
|
103 |
|
104 | router.post(
|
105 | '/email/subscribe.:ext?',
|
106 | asyncMiddleware(async (req, res) => {
|
107 | const email = Email(await getConfig(req.session.slug));
|
108 |
|
109 | try {
|
110 | handleResponse(req, res, await email.subscribe({
|
111 | email: req.body.email || req.query.email,
|
112 | name: req.body.name || req.query.name || '',
|
113 | }));
|
114 | } catch (error) {
|
115 | handleError(req, res, error);
|
116 | }
|
117 | })
|
118 | );
|
119 | };
|