UNPKG

3.1 kBJavaScriptView Raw
1module.exports = ({
2 Email,
3 Entity,
4 router,
5 asyncMiddleware,
6 getConfig,
7 handleResponse,
8 handleError,
9}) => {
10
11 /**
12 * @swagger
13 * /email/template:
14 * get:
15 * tags:
16 * - email
17 * summary: Render email template
18 * # description: Render email template
19 * produces:
20 * - text/html
21 * parameters:
22 * - name: slug
23 * description: Slug (parent folder name of the template)
24 * in: query
25 * required: false
26 * type: string
27 * - name: templateSlug
28 * description: Template slug (folder name of the template)
29 * in: query
30 * required: true
31 * type: string
32 * - name: entityId
33 * description: Entity `id` from which to render the template
34 * in: query
35 * required: false
36 * type: string
37 * - name: preview
38 * description: Preview mode (disable inlining of styles etc)
39 * in: query
40 * required: false
41 * type: boolean
42 * responses:
43 * 200:
44 * description: Template
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};