Refactor EmailService to inject dependencies

This commit is contained in:
Alex Holliday committed 2024-10-17 14:00:22 +08:00
1 parent ab0f4e49bc
commit 17ed90f76b
1 file changed
+123 -122
+123 -122
View File
@@ -1,11 +1,6 @@
import fs from "fs";
import path from "path";
import nodemailer from "nodemailer";
import pkg from "handlebars";
const { compile } = pkg;
import mjml2html from "mjml";
import logger from "../utils/logger.js";
import { fileURLToPath } from "url"; import { fileURLToPath } from "url";
import path from "path";
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); const __dirname = path.dirname(__filename);
@@ -15,128 +10,134 @@ const SERVICE_NAME = "EmailService";
* Represents an email service that can load templates, build, and send emails. * Represents an email service that can load templates, build, and send emails.
*/ */
class EmailService { class EmailService {
/** /**
* Constructs an instance of the EmailService, initializing template loaders and the email transporter. * Constructs an instance of the EmailService, initializing template loaders and the email transporter.
*/ * @param {Object} settingsService - The settings service to get email configuration.
constructor(settingsService) { * @param {Object} fs - The file system module.
this.settingsService = settingsService; * @param {Object} path - The path module.
/** * @param {Function} compile - The Handlebars compile function.
* Loads an email template from the filesystem. * @param {Function} mjml2html - The MJML to HTML conversion function.
* * @param {Object} nodemailer - The nodemailer module.
* @param {string} templateName - The name of the template to load. * @param {Object} logger - The logger module.
* @returns {Function} A compiled template function that can be used to generate HTML email content. */
*/ constructor(settingsService, fs, path, compile, mjml2html, nodemailer, logger) {
this.loadTemplate = (templateName) => { this.settingsService = settingsService;
try { this.fs = fs;
const templatePath = path.join( this.path = path;
__dirname, this.compile = compile;
`../templates/${templateName}.mjml` this.mjml2html = mjml2html;
); this.nodemailer = nodemailer;
const templateContent = fs.readFileSync(templatePath, "utf8"); this.logger = logger;
return compile(templateContent);
} catch (error) {
logger.error("Error loading Email templates", {
error,
service: this.SERVICE_NAME,
});
}
};
/** /**
* A lookup object to access preloaded email templates. * Loads an email template from the filesystem.
* @type {Object.<string, Function>} *
* TODO Load less used templates in their respective functions * @param {string} templateName - The name of the template to load.
*/ * @returns {Function} A compiled template function that can be used to generate HTML email content.
this.templateLookup = { */
welcomeEmailTemplate: this.loadTemplate("welcomeEmail"), this.loadTemplate = (templateName) => {
employeeActivationTemplate: this.loadTemplate("employeeActivation"), try {
noIncidentsThisWeekTemplate: this.loadTemplate("noIncidentsThisWeek"), const templatePath = this.path.join(
serverIsDownTemplate: this.loadTemplate("serverIsDown"), __dirname,
serverIsUpTemplate: this.loadTemplate("serverIsUp"), `../templates/${templateName}.mjml`
passwordResetTemplate: this.loadTemplate("passwordReset"), );
}; const templateContent = this.fs.readFileSync(templatePath, "utf8");
return this.compile(templateContent);
} catch (error) {
logger.error("Error loading Email templates", {
error,
service: this.SERVICE_NAME,
});
}
};
/** /**
* The email transporter used to send emails. * A lookup object to access preloaded email templates.
* @type {Object} * @type {Object.<string, Function>}
*/ * TODO Load less used templates in their respective functions
*/
this.templateLookup = {
welcomeEmailTemplate: this.loadTemplate("welcomeEmail"),
employeeActivationTemplate: this.loadTemplate("employeeActivation"),
noIncidentsThisWeekTemplate: this.loadTemplate("noIncidentsThisWeek"),
serverIsDownTemplate: this.loadTemplate("serverIsDown"),
serverIsUpTemplate: this.loadTemplate("serverIsUp"),
passwordResetTemplate: this.loadTemplate("passwordReset"),
};
const { /**
systemEmailHost, * The email transporter used to send emails.
systemEmailPort, * @type {Object}
systemEmailAddress, */
systemEmailPassword,
} = this.settingsService.getSettings();
const emailConfig = { const { systemEmailHost, systemEmailPort, systemEmailAddress, systemEmailPassword } =
host: systemEmailHost, this.settingsService.getSettings();
port: systemEmailPort,
secure: true,
auth: {
user: systemEmailAddress,
pass: systemEmailPassword,
},
};
this.transporter = nodemailer.createTransport(emailConfig); const emailConfig = {
} host: systemEmailHost,
port: systemEmailPort,
secure: true,
auth: {
user: systemEmailAddress,
pass: systemEmailPassword,
},
};
/** this.transporter = this.nodemailer.createTransport(emailConfig);
* Asynchronously builds and sends an email using a specified template and context. }
*
* @param {string} template - The name of the template to use for the email body.
* @param {Object} context - The data context to render the template with.
* @param {string} to - The recipient's email address.
* @param {string} subject - The subject of the email.
* @returns {Promise<string>} A promise that resolves to the messageId of the sent email.
*/
buildAndSendEmail = async (template, context, to, subject) => {
const buildHtml = async (template, context) => {
try {
const mjml = this.templateLookup[template](context);
const html = await mjml2html(mjml);
return html.html;
} catch (error) {
logger.error("Error building Email HTML", {
error,
service: SERVICE_NAME,
});
}
};
const sendEmail = async (to, subject, html) => { /**
try { * Asynchronously builds and sends an email using a specified template and context.
const info = await this.transporter.sendMail({ *
to: to, * @param {string} template - The name of the template to use for the email body.
subject: subject, * @param {Object} context - The data context to render the template with.
html: html, * @param {string} to - The recipient's email address.
}); * @param {string} subject - The subject of the email.
return info; * @returns {Promise<string>} A promise that resolves to the messageId of the sent email.
} catch (error) { */
logger.error("Error sending Email", { buildAndSendEmail = async (template, context, to, subject) => {
error, const buildHtml = async (template, context) => {
service: SERVICE_NAME, try {
}); const mjml = this.templateLookup[template](context);
} const html = await this.mjml2html(mjml);
}; return html.html;
} catch (error) {
logger.error("Error building Email HTML", {
error,
service: SERVICE_NAME,
});
}
};
try { const sendEmail = async (to, subject, html) => {
const info = await sendEmail( try {
to, const info = await this.transporter.sendMail({
subject, to: to,
await buildHtml(template, context) subject: subject,
); html: html,
return info.messageId; });
} catch (error) { return info;
error.service = SERVICE_NAME; } catch (error) {
if (error.method === undefined) { logger.error("Error sending Email", {
error.method = "buildAndSendEmail"; error,
} service: SERVICE_NAME,
logger.error("Error building and sending Email", { });
error, }
service: SERVICE_NAME, };
});
} try {
}; const info = await sendEmail(to, subject, await buildHtml(template, context));
return info.messageId;
} catch (error) {
error.service = SERVICE_NAME;
if (error.method === undefined) {
error.method = "buildAndSendEmail";
}
logger.error("Error building and sending Email", {
error,
service: SERVICE_NAME,
});
}
};
} }
export default EmailService; export default EmailService;