zents
Version:
ZenTS is a Node.js & TypeScript MVC-Framework for building rich web applications, released as free and open-source software under the MIT License. It is designed for building web applications with modern tools and design patterns.
62 lines • 2.83 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmailFactory = void 0;
const config_1 = require("../config/config");
const nodemailer_1 = require("nodemailer");
const html_to_text_1 = require("html-to-text");
const logger_1 = require("../log/logger");
const mjml_1 = __importDefault(require("mjml"));
const nunjucks_1 = require("nunjucks");
class EmailFactory {
constructor(emailTemplates) {
var _a;
this.emailTemplates = emailTemplates;
if ((_a = config_1.config.email) === null || _a === void 0 ? void 0 : _a.enable) {
this.transporter = nodemailer_1.createTransport(config_1.config.email);
}
else {
this.transporter = null;
}
}
async send(options) {
var _a, _b, _c, _d, _e;
if (this.transporter === null) {
throw new Error('Trying to send an E-Mail without proper email configuration. Please enable email in your ZenTS configuration before sending emails');
}
else if (!this.emailTemplates.has(options.template)) {
throw new Error(`Email template "${options.template}" not found!`);
}
const engine = (_a = options.engine) !== null && _a !== void 0 ? _a : config_1.config.email.engine;
const { template, payload } = options;
let content = this.emailTemplates.get(template);
if (engine !== 'plain') {
content = nunjucks_1.renderString(content, payload);
}
if (engine === 'mjml') {
const result = mjml_1.default(content, (_b = config_1.config.email) === null || _b === void 0 ? void 0 : _b.mjml);
if (result.errors.length) {
logger_1.log.error(result.errors);
throw new Error('Failed to render MJML! See error(s) above for more information.');
}
content = result.html;
}
const data = typeof config_1.config.email.mailOptions === 'undefined'
? options
: Object.assign({}, config_1.config.email.mailOptions, options);
if (engine !== 'plain') {
data.html = content;
if ((_d = (_c = config_1.config.email) === null || _c === void 0 ? void 0 : _c.htmlToText) === null || _d === void 0 ? void 0 : _d.enable) {
data.text = html_to_text_1.htmlToText(content, (_e = config_1.config.email) === null || _e === void 0 ? void 0 : _e.htmlToText);
}
}
else if (!data.keepText) {
data.text = content;
}
return (await this.transporter.sendMail(data));
}
}
exports.EmailFactory = EmailFactory;
//# sourceMappingURL=EmailFactory.js.map