all repos — caroster @ 129bfe7ea037f0a0d837d009892bda761812a588

[Octree] Group carpool to your event https://caroster.io

backend/src/api/email/services/email.ts (view raw)

  1import fs from "node:fs/promises";
  2import _ from "lodash";
  3import { marked } from "marked";
  4import { getHTMLMeta } from "../utils/layout";
  5
  6const langs = ["en", "fr"];
  7
  8let locales: Record<
  9  string,
 10  {
 11    template: Record<"header" | "footer", 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 mdHeader = locales?.[lang]?.template.header;
 83      const mdFooter = locales?.[lang]?.template.footer;
 84      const htmlContent = await marked.parse(mdContent, { breaks: true });
 85      const htmlHeader = await marked.parse(mdHeader, { breaks: true });
 86      const htmlFooter = await marked.parse(mdFooter, { breaks: true });
 87      const html = `<header>${htmlHeader}</header><main>${getHTMLMeta()}${htmlContent}${htmlFooter}</main>`;
 88
 89      return {
 90        subject,
 91        html,
 92        text: notif.content,
 93      };
 94    } catch (error) {
 95      strapi.log.error(
 96        `Can't parse email notification locale for type '${notifType}' and lang '${lang}'`
 97      );
 98      console.error(error);
 99      return null;
100    }
101  },
102});