Files
Checkmate/Server/models/Check.js
T

63 lines
1.4 KiB
JavaScript
Raw Normal View History

const mongoose = require("mongoose");
const CheckSchema = mongoose.Schema(
{
monitorId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Monitor",
immutable: true,
},
status: {
type: Boolean,
},
responseTime: {
type: Number, // milliseconds
},
statusCode: {
type: Number, // 200, ... , 500
},
message: {
type: String,
},
expiry: {
type: Date,
default: Date.now,
expires: 60 * 60 * 24 * 30, // 30 days in seconds
},
},
{
timestamps: true,
}
);
2024-07-03 11:46:30 -07:00
/**
* When a check is created, we should update the stauts of the associated monitor
* if it has changed. Monitor starts with default status: true
2024-07-03 12:34:57 -07:00
* @param {function} next - Callback to proceed to the next middleware.
2024-07-03 11:46:30 -07:00
*/
CheckSchema.pre("save", async function (next) {
2024-07-03 12:32:42 -07:00
try {
const monitor = await mongoose.model("Monitor").findById(this.monitorId);
if (monitor && monitor.status !== this.status) {
if (monitor.status === true && this.status === false) {
// TODO issue alert
console.log("Monitor went down");
}
2024-07-03 11:46:30 -07:00
2024-07-03 12:32:42 -07:00
if (monitor.status === false && this.status === true) {
// TODO issue alert
console.log("Monitor went up");
}
2024-07-03 13:19:47 -07:00
monitor.status = this.status;
2024-07-03 12:32:42 -07:00
await monitor.save();
2024-07-03 11:46:30 -07:00
}
2024-07-03 12:32:42 -07:00
} catch (error) {
console.log(error);
} finally {
next();
}
});
module.exports = mongoose.model("Check", CheckSchema);