Refactored notifications from Check model to NetworkService

This commit is contained in:
Alex Holliday committed 2024-08-14 10:20:35 -07:00
1 parent a6116da278
commit 809e6ee58f
5 files changed
+59 -129

No files matched your search

-57
View File
@@ -69,61 +69,4 @@ const CheckSchema = mongoose.Schema(
}
);
/**
* Pre-save middleware to handle status change notifications.
*
* This middleware checks if the status of the monitor associated
* with the check has changed and sends notifications if necessary.
*/
CheckSchema.pre("save", async function (next) {
try {
const monitor = await mongoose.model("Monitor").findById(this.monitorId);
if (monitor) {
const notifications = await Notification.find({
monitorId: this.monitorId,
});
// Check if there are any notifications
// Only send email if monitor status has changed
if (monitor.status !== this.status) {
const emailService = new EmailService();
let template = "";
let status = "";
if (monitor.status === true && this.status === false) {
template = "serverIsDownTemplate";
status = "down";
}
if (monitor.status === false && this.status === true) {
// Notify users that the monitor is up
template = "serverIsUpTemplate";
status = "up";
}
for (const notification of notifications) {
if (notification.type === "email") {
await emailService.buildAndSendEmail(
template,
{ monitorName: monitor.name, monitorUrl: monitor.url },
notification.address,
`Monitor ${monitor.name} is ${status}`
);
}
}
// Update monitor status
monitor.status = this.status;
await monitor.save();
}
}
} catch (error) {
console.log(error);
} finally {
next();
}
});
module.exports = mongoose.model("Check", CheckSchema);