@openinc/parse-server-opendash
Version:
Parse Server Cloud Code for open.INC Stack.
84 lines (83 loc) • 2.91 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendSimpleEmail = sendSimpleEmail;
exports.sendTemplateEmail = sendTemplateEmail;
const fs_1 = __importDefault(require("fs"));
const nunjucks_1 = __importDefault(require("nunjucks"));
const path_1 = require("path");
const types_1 = require("../../../types");
const EmailState_1 = require("../states/EmailState");
/**
* Send a simple email
* @param to The recipient email address
* @param subject The subject of the email
* @param text The plain text content of the email
* @returns The saved email object
*/
async function sendSimpleEmail(to, subject, text) {
const email = new types_1.Core_Email({
payload: {
to,
subject,
text,
},
});
await email.save(null, { useMasterKey: true });
return email;
}
/**
* Send a template email
* @param param0
* @returns
*/
async function sendTemplateEmail({ to, subject, fallback, template, data, }) {
const email = new types_1.Core_Email({
payload: {
to,
subject: renderEmailTemplate("subject", template, data, subject),
text: renderEmailTemplate("txt", template, data, fallback),
html: renderEmailTemplate("html", template, data, undefined),
},
});
await email.save(null, { useMasterKey: true });
return email;
}
/**
* Validate if an email template exists in the specified directory
* @param templateDir The directory where email templates are stored
* @param template The specific template file to validate
* @returns Whether the template exists in the directory
*/
function validateEmailTemplate(templateDir, template) {
const templatePath = (0, path_1.join)(templateDir, template);
if (!fs_1.default.existsSync(templateDir)) {
return false;
}
if (!fs_1.default.existsSync(templatePath)) {
return false;
}
return true;
}
/**
* Render an email template
* @param type The type of the email template (txt, html, subject)
* @param template The base name of the template file
* @param data The data to be used for rendering the template
* @param fallback The fallback content if the template is not found
* @returns The rendered email content
*/
function renderEmailTemplate(type, template, data, fallback) {
const emailState = EmailState_1.EmailState.getInstance();
const emailTemplateDir = emailState.getEmailTemplateDir();
const fullTemplate = template + "." + type;
if (validateEmailTemplate(emailTemplateDir, fullTemplate)) {
return nunjucks_1.default.render(fullTemplate, data);
}
if (type === "html") {
return renderEmailTemplate("txt", template, data, fallback);
}
return fallback || "";
}