look up notifications by monitor and not by user.

This commit is contained in:
M M committed 2024-08-06 19:35:03 -07:00
1 parent e6fac616db
commit 66d101877a
1 file changed
+25 -20
+25 -20
View File
@@ -34,39 +34,43 @@ 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) { if (monitor) {
// Check if the monitor has notifications // Check if the monitor has notifications
if (monitor.notifications && monitor.notifications.length > 0) { if (monitor.notifications && monitor.notifications.length > 0) {
// Only send email if monitor status has changed
if (monitor.status !== this.status) { if (monitor.status !== this.status) {
const emailService = new EmailService(); 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 users that the monitor is down
const users = await mongoose.model("User").find({ _id: monitor.userId }); for (const notification of monitor.notifications) {
if (users.length > 0) { if (notification.email) {
const user = users[0]; await emailService.buildAndSendEmail(
await emailService.buildAndSendEmail( "serverIsDownTemplate",
"serverIsDownTemplate", { monitorName: monitor.name, monitorUrl: monitor.url },
{ monitorName: monitor.name, monitorUrl: monitor.url }, notification.email,
user.email, `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 users that the monitor is up
const users = await mongoose.model("User").find({ _id: monitor.userId }); for (const notification of monitor.notifications) {
if (users.length > 0) { if (notification.email) {
const user = users[0]; await emailService.buildAndSendEmail(
await emailService.buildAndSendEmail( "serverIsUpTemplate",
"serverIsUpTemplate", { monitorName: monitor.name, monitorUrl: monitor.url },
{ monitorName: monitor.name, monitorUrl: monitor.url }, notification.email,
user.email, `Monitor ${monitor.name} is back up`
`Monitor ${monitor.name} is back up` );
); }
} }
} }
// Update monitor status
monitor.status = this.status; monitor.status = this.status;
await monitor.save(); await monitor.save();
} }
@@ -80,4 +84,5 @@ CheckSchema.pre("save", async function (next) {
}); });
module.exports = mongoose.model("Check", CheckSchema); module.exports = mongoose.model("Check", CheckSchema);