Fixed bug that sends an email even if a user does not have notifications turned on.

This commit is contained in:
M M committed 2024-08-06 18:58:13 -07:00
1 parent 3bcf564ee4
commit e6fac616db
1 file changed
+13 -5
+13 -5
View File
@@ -34,13 +34,17 @@ const CheckSchema = mongoose.Schema(
CheckSchema.pre("save", async function (next) { CheckSchema.pre("save", async function (next) {
try { try {
const monitor = await mongoose.model("Monitor").findById(this.monitorId); const monitor = await mongoose.model("Monitor").findById(this.monitorId);
if (monitor && monitor.status !== this.status) { if (monitor) {
// Check if the monitor has notifications
if (monitor.notifications && monitor.notifications.length > 0) {
if (monitor.status !== this.status) {
const emailService = new EmailService();
if (monitor.status === true && this.status === false) { if (monitor.status === true && this.status === false) {
// Notify user that the monitor is down // Notify user that the monitor is down
const emailService = new EmailService();
const users = await mongoose.model("User").find({ _id: monitor.userId }); const users = await mongoose.model("User").find({ _id: monitor.userId });
if (users.length > 0) {
const user = users[0]; const user = users[0];
await emailService.buildAndSendEmail( await emailService.buildAndSendEmail(
"serverIsDownTemplate", "serverIsDownTemplate",
{ monitorName: monitor.name, monitorUrl: monitor.url }, { monitorName: monitor.name, monitorUrl: monitor.url },
@@ -48,13 +52,13 @@ CheckSchema.pre("save", async function (next) {
`Monitor ${monitor.name} is down` `Monitor ${monitor.name} is down`
); );
} }
}
if (monitor.status === false && this.status === true) { if (monitor.status === false && this.status === true) {
// Notify user that the monitor is up // Notify user that the monitor is up
const emailService = new EmailService();
const users = await mongoose.model("User").find({ _id: monitor.userId }); const users = await mongoose.model("User").find({ _id: monitor.userId });
if (users.length > 0) {
const user = users[0]; const user = users[0];
await emailService.buildAndSendEmail( await emailService.buildAndSendEmail(
"serverIsUpTemplate", "serverIsUpTemplate",
{ monitorName: monitor.name, monitorUrl: monitor.url }, { monitorName: monitor.name, monitorUrl: monitor.url },
@@ -62,9 +66,12 @@ CheckSchema.pre("save", async function (next) {
`Monitor ${monitor.name} is back up` `Monitor ${monitor.name} is back up`
); );
} }
}
monitor.status = this.status; monitor.status = this.status;
await monitor.save(); await monitor.save();
} }
}
}
} catch (error) { } catch (error) {
console.log(error); console.log(error);
} finally { } finally {
@@ -72,4 +79,5 @@ CheckSchema.pre("save", async function (next) {
} }
}); });
module.exports = mongoose.model("Check", CheckSchema); module.exports = mongoose.model("Check", CheckSchema);