backend/src/api/email/services/email.ts (view raw)
1import fs from "node:fs/promises";
2import _ from "lodash";
3import { marked } from "marked";
4import { getHTML } from "../utils/layout";
5
6const langs = ["en", "fr", "nl"];
7
8let locales: Record<
9 string,
10 {
11 template: Record<"footer" | "carosterLink", string>;
12 notifications: Record<string, { title: string; content: string }>;
13 }
14> = null;
15
16export default () => ({
17 async loadContentFiles() {
18 strapi.log.info(
19 `🌐 Load localized content files for email notifications...`
20 );
21 const content = await Promise.all(
22 langs.map(async (lang) => {
23 const langFile = await fs.readFile(
24 `${__dirname}/../locales/${lang}.json`,
25 "utf-8"
26 );
27 return [lang, JSON.parse(langFile)];
28 })
29 );
30 locales = Object.fromEntries(content);
31 return locales;
32 },
33
34 async sendEmailNotif(
35 to: string,
36 notifType: string,
37 lang: string,
38 variables?: object
39 ) {
40 try {
41 const emailTemplate = await this.getEmailTemplate(
42 notifType,
43 lang,
44 variables
45 );
46 if (!emailTemplate)
47 throw new Error(`No locale found for ${notifType} in ${lang}`);
48
49 strapi.log.debug(
50 `Send email notification of type ${notifType} to ${to} (lang: ${lang})`
51 );
52 await strapi.plugins["email"].services.email.send({
53 to,
54 ...emailTemplate,
55 });
56 } catch (error) {
57 strapi.log.error(`Can't send email notification to ${to}`);
58 console.error(error);
59 }
60 },
61
62 async getEmailTemplate(notifType: string, lang: string, variables = {}) {
63 let notif = locales?.[lang]?.notifications?.[notifType];
64
65 if (!notif) {
66 strapi.log.warn(
67 `No email notification locale found for type '${notifType}' and lang '${lang}'`
68 );
69 notif = locales?.["en"]?.notifications?.[notifType];
70 if (!notif) return null;
71 }
72
73 try {
74 const subject = _.template(notif.title)({
75 ...variables,
76 host: strapi.config.server.url,
77 });
78 const mdContent = _.template(notif.content)({
79 ...variables,
80 host: strapi.config.server.url,
81 });
82 const mdFooter = locales?.[lang]?.template.footer;
83 const carosterLink = locales?.[lang]?.template.carosterLink;
84 const htmlContent = await marked.parse(mdContent, { breaks: true });
85 const htmlFooter = await marked.parse(mdFooter, { breaks: true });
86 const html = getHTML({htmlContent, htmlFooter, carosterLink});
87
88 return {
89 subject,
90 html,
91 text: mdContent,
92 };
93 } catch (error) {
94 strapi.log.error(
95 `Can't parse email notification locale for type '${notifType}' and lang '${lang}'`
96 );
97 console.error(error);
98 return null;
99 }
100 },
101});