Refactored email service for modernity and clarity

This commit is contained in:
Alex Holliday committed 2024-07-19 14:35:50 -07:00
1 parent cb2961b9d6
commit 1c3c7e115a
2 files changed
+76 -165

No files matched your search

+28 -51
View File
@@ -1,26 +1,24 @@
const express = require("express"); const express = require("express");
const helmet = require("helmet"); const helmet = require("helmet");
const cors = require("cors"); const cors = require("cors");
const authRouter = require("./routes/authRoute");
const monitorRouter = require("./routes/monitorRoute");
const checkRouter = require("./routes/checkRoute");
const alertRouter = require("./routes/alertRoute");
const { connectDbAndRunServer } = require("./configs/db");
require("dotenv").config(); require("dotenv").config();
const logger = require("./utils/logger"); const logger = require("./utils/logger");
const { verifyJWT } = require("./middleware/verifyJWT"); const { verifyJWT } = require("./middleware/verifyJWT");
const { handleErrors } = require("./middleware/handleErrors"); const { handleErrors } = require("./middleware/handleErrors");
const authRouter = require("./routes/authRoute");
const monitorRouter = require("./routes/monitorRoute");
const checkRouter = require("./routes/checkRoute");
const alertRouter = require("./routes/alertRoute");
const pageSpeedCheckRouter = require("./routes/pageSpeedCheckRoute");
const { connectDbAndRunServer } = require("./configs/db");
const queueRouter = require("./routes/queueRoute"); const queueRouter = require("./routes/queueRoute");
const JobQueue = require("./service/jobQueue"); const JobQueue = require("./service/jobQueue");
const pageSpeedCheckRouter = require("./routes/pageSpeedCheckRoute"); const EmailService = require("./service/emailService");
const nodemailer = require("nodemailer");
const emailService = require("./service/emailService");
// Need to wrap server setup in a function to handle async nature of JobQueue // Need to wrap server setup in a function to handle async nature of JobQueue
const startApp = async () => { const startApp = async () => {
// const { sendEmail } = require('./utils/sendEmail')
// ************************** // **************************
// Here is where we can swap out DBs easily. Spin up a mongoDB instance and try it out. // Here is where we can swap out DBs easily. Spin up a mongoDB instance and try it out.
// Simply comment out the FakeDB and uncomment the MongoDB or vice versa. // Simply comment out the FakeDB and uncomment the MongoDB or vice versa.
@@ -42,12 +40,6 @@ const startApp = async () => {
? DB_TYPE[process.env.DB_TYPE]() ? DB_TYPE[process.env.DB_TYPE]()
: require("./db/FakeDb"); : require("./db/FakeDb");
/**
* NOTES
* Email Service will be added
* Logger Service will be added (Winston or similar)
*/
const app = express(); const app = express();
// middlewares // middlewares
@@ -62,11 +54,12 @@ const startApp = async () => {
// Make DB accessible anywhere we have a Request object // Make DB accessible anywhere we have a Request object
// By adding the DB to the request object, we can access it in any route // By adding the DB to the request object, we can access it in any route
// Thus we do not need to import it in every route file, and we can easily swap out DBs as there is only one place to change it // Thus we do not need to import it in every route file, and we can easily swap out DBs as there is only one place to change it
// Same applies for JobQueue // Same applies for JobQueue and emailService
// ************************** // **************************
app.use((req, res, next) => { app.use((req, res, next) => {
req.db = db; req.db = db;
req.jobQueue = jobQueue; req.jobQueue = jobQueue;
req.emailSerivce = emailSerivce;
next(); next();
}); });
@@ -90,39 +83,21 @@ const startApp = async () => {
} }
}); });
// Nodemailer code here app.use("/api/v1/mail", async (req, res) => {
const transporter = nodemailer.createTransport({ try {
host: process.env.EMAIL_SERVICE_HOST, const id = await req.emailSerivce.buildAndSendEmail(
port: process.env.EMAIL_SERVICE_PORT, "welcomeEmailTemplate",
auth: { {
user: process.env.EMAIL_SERVICE_USERNAME, name: "Alex",
pass: process.env.EMAIL_SERVICE_PASSWORD, },
}, "ajhollid@gmail.com",
}); "Welcome"
);
app.use("/api/v1/mail", (req, res) => { res.status(200).json({ success: true, msg: "Email sent", data: id });
console.log("Started"); } catch (error) {
// Replacing varibales logger.error(error.message);
const context = { name: "Alex" }; return res.status(500).json({ message: error.message });
}
// Define mail options
const mailOptions = {
from: "BlueWave Uptime <bluewaveuptime@gmail.com>", // sender address
to: "muhammadkhalilzadeh1998@gmailc.com", // list of receivers
subject: "Testing template emails", // Subject line
html: emailService.sendWelcomeEmail(context), // html body
};
// Send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return res
.status(500)
.send({ message: "Error sending email", error: error });
}
console.log(info);
res.status(200).send({ message: "Email sent successfully", info: info });
});
}); });
/** /**
@@ -131,8 +106,10 @@ const startApp = async () => {
*/ */
app.use(handleErrors); app.use(handleErrors);
// Create services
await connectDbAndRunServer(app, db); await connectDbAndRunServer(app, db);
const jobQueue = await JobQueue.createJobQueue(db); const jobQueue = await JobQueue.createJobQueue(db);
const emailSerivce = new EmailService();
const cleanup = async () => { const cleanup = async () => {
console.log("Shutting down gracefully"); console.log("Shutting down gracefully");
+48 -114
View File
@@ -1,125 +1,59 @@
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const nodemailer = require("nodemailer");
const { compile } = require("handlebars"); const { compile } = require("handlebars");
const { mjml2html } = require("mjml"); const { mjml2html } = require("mjml");
// Fetching Templates class EmailService {
constructor() {
this.loadTemplate = (templateName) => {
const templatePath = path.join(
__dirname,
`../templates/${templateName}.mjml`
);
const templateContent = fs.readFileSync(templatePath, "utf8");
return compile(templateContent);
};
// Welcome Email Template // TODO Load less used templates in their respective functions
const welcomeEmailTemplatePath = path.join( this.templateLookup = {
__dirname, welcomeEmailTemplate: this.loadTemplate("welcomeEmail"),
"../templates/welcomeEmail.mjml" employeeActivationTemplate: this.loadTemplate("employeeActivation"),
); noIncidentsThisWeekTemplate: this.loadTemplate("noIncidentsThisWeek"),
const welcomeEmailTemplateContent = fs.readFileSync( serverIsDownTemplate: this.loadTemplate("serverIsDown"),
welcomeEmailTemplatePath, serverIsUpTemplate: this.loadTemplate("serverIsUp"),
"utf8" passwordResetTemplate: this.loadTemplate("passwordReset"),
); };
const welcomeEmailTemplate = compile(welcomeEmailTemplateContent);
// Employee Activation Email Template this.transporter = nodemailer.createTransport({
const employeeActivationTemplatePath = path.join( host: process.env.EMAIL_SERVICE_HOST,
__dirname, port: process.env.EMAIL_SERVICE_PORT,
"../templates/employeeActivation.mjml" secure: true, // Use `true` for port 465, `false` for all other ports
); auth: {
const employeeActivationTemplateContent = fs.readFileSync( user: process.env.EMAIL_SERVICE_USERNAME,
employeeActivationTemplatePath, pass: process.env.EMAIL_SERVICE_PASSWORD,
"utf8" },
); });
const employeeActivation = compile(employeeActivationTemplateContent); }
// No Incident This Week Template buildAndSendEmail = async (template, context, to, subject) => {
const noIncidentsThisWeekTemplatePath = path.join( const buildHtml = (template, context) => {
__dirname, const mjml = this.templateLookup[template](context);
"../templates/noIncidentsThisWeek.mjml" const html = mjml2html(mjml);
); return html;
const noIncidentsThisWeekTemplateContent = fs.readFileSync( };
noIncidentsThisWeekTemplatePath,
"utf8"
);
const noIncidentsThisWeek = compile(noIncidentsThisWeekTemplateContent);
// Server is Down Template const sendEmail = async (to, subject, html) => {
const serverIsDownTemplatePath = path.join( const info = await this.transporter.sendMail({
__dirname, to: to,
"../templates/serverIsDown.mjml" subject: subject,
); html: html,
const serverIsDownTemplateContent = fs.readFileSync( });
serverIsDownTemplatePath, return info;
"utf8" };
); const info = await sendEmail(to, subject, buildHtml(template, context));
const serverIsDown = compile(serverIsDownTemplateContent); return info.messageId;
};
// Server is Up Template
const serverIsUpTemplatePath = path.join(
__dirname,
"../templates/serverIsUp.mjml"
);
const serverIsUpTemplateContent = fs.readFileSync(
serverIsUpTemplatePath,
"utf8"
);
const serverIsUp = compile(serverIsUpTemplateContent);
// Password Reset Template
const passwordResetTemplatePath = path.join(
__dirname,
"../templates/passwordReset.mjml"
);
const passwordResetTemplateContent = fs.readFileSync(
passwordResetTemplatePath,
"utf8"
);
const passwordReset = compile(passwordResetTemplateContent);
// *** Application specific functions ***
function sendWelcomeEmail(context) {
const mjml = welcomeEmailTemplate(context);
const html = mjml2html(mjml);
return html;
} }
function sendEmployeeActivationEmail(context) { module.exports = EmailService;
const mjml = employeeActivation(context);
const html = mjml2html(mjml);
return html;
}
function sendNoIncidentsThisWeekEmail(context) {
const mjml = noIncidentsThisWeek(context);
const html = mjml2html(mjml);
return html;
}
function sendServerIsDownEmail(context) {
const mjml = serverIsDown(context);
const html = mjml2html(mjml);
return html;
}
function sendServerIsUpEmail(context) {
const mjml = serverIsUp(context);
const html = mjml2html(mjml);
return html;
}
function sendPasswordResetEmail(context) {
const mjml = passwordReset(context);
const html = mjml2html(mjml);
return html;
}
module.exports = {
sendWelcomeEmail,
sendEmployeeActivationEmail,
sendNoIncidentsThisWeekEmail,
sendServerIsDownEmail,
sendServerIsUpEmail,
sendPasswordResetEmail,
};