Merge branch 'develop' into feat/super-simple-queue
This commit is contained in:
commit
4f186a6b49
189 files changed
+4473
-5400
No files matched your search
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"printWidth": 90,
|
||||
"printWidth": 150,
|
||||
"useTabs": true,
|
||||
"tabWidth": 2,
|
||||
"singleQuote": false,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createAnnouncementValidation } from "../validation/joi.js";
|
||||
import { handleError } from "./controllerUtils.js";
|
||||
import { asyncHandler } from "../utils/errorUtils.js";
|
||||
|
||||
const SERVICE_NAME = "announcementController";
|
||||
|
||||
@@ -28,16 +28,10 @@ class AnnouncementController {
|
||||
*
|
||||
* @returns {Promise<void>} A promise that resolves once the response is sent.
|
||||
*/
|
||||
createAnnouncement = async (req, res, next) => {
|
||||
try {
|
||||
createAnnouncement = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await createAnnouncementValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
return next(handleError(error, SERVICE_NAME)); // Handle Joi validation errors
|
||||
}
|
||||
|
||||
const { title, message } = req.body;
|
||||
|
||||
try {
|
||||
const { title, message } = req.body;
|
||||
const announcementData = {
|
||||
title: title.trim(),
|
||||
message: message.trim(),
|
||||
@@ -49,10 +43,10 @@ class AnnouncementController {
|
||||
msg: this.stringService.createAnnouncement,
|
||||
data: newAnnouncement,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "createAnnouncement"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"createAnnouncement"
|
||||
);
|
||||
|
||||
/**
|
||||
* Handles retrieving announcements with pagination.
|
||||
@@ -63,17 +57,17 @@ class AnnouncementController {
|
||||
* - `msg`: A message about the success of the request.
|
||||
* @param {Function} next - The next middleware function in the stack for error handling.
|
||||
*/
|
||||
getAnnouncement = async (req, res, next) => {
|
||||
try {
|
||||
getAnnouncement = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const allAnnouncements = await this.db.getAnnouncements();
|
||||
return res.success({
|
||||
msg: this.stringService.getAnnouncement,
|
||||
data: allAnnouncements,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getAnnouncement"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getAnnouncement"
|
||||
);
|
||||
}
|
||||
|
||||
export default AnnouncementController;
|
||||
@@ -1,16 +1,20 @@
|
||||
import {
|
||||
registrationBodyValidation,
|
||||
loginValidation,
|
||||
editUserParamValidation,
|
||||
editUserBodyValidation,
|
||||
recoveryValidation,
|
||||
recoveryTokenValidation,
|
||||
newPasswordValidation,
|
||||
getUserByIdParamValidation,
|
||||
editUserByIdParamValidation,
|
||||
editUserByIdBodyValidation,
|
||||
editSuperadminUserByIdBodyValidation,
|
||||
} from "../validation/joi.js";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { getTokenFromHeaders } from "../utils/utils.js";
|
||||
import crypto from "crypto";
|
||||
import { handleValidationError, handleError } from "./controllerUtils.js";
|
||||
import { asyncHandler, createAuthError, createError } from "../utils/errorUtils.js";
|
||||
|
||||
const SERVICE_NAME = "authController";
|
||||
|
||||
class AuthController {
|
||||
@@ -32,15 +36,10 @@ class AuthController {
|
||||
* @throws {Error}
|
||||
*/
|
||||
issueToken = (payload, appSettings) => {
|
||||
try {
|
||||
const tokenTTL = appSettings?.jwtTTL ?? "2h";
|
||||
const tokenSecret = appSettings?.jwtSecret;
|
||||
const payloadData = payload;
|
||||
|
||||
return jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
|
||||
} catch (error) {
|
||||
throw handleError(error, SERVICE_NAME, "issueToken");
|
||||
}
|
||||
const tokenTTL = appSettings?.jwtTTL ?? "2h";
|
||||
const tokenSecret = appSettings?.jwtSecret;
|
||||
const payloadData = payload;
|
||||
return jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -55,19 +54,14 @@ class AuthController {
|
||||
* @returns {Object} The response object with a success status, a message indicating the creation of the user, the created user data, and a JWT token.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
registerUser = async (req, res, next) => {
|
||||
try {
|
||||
registerUser = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
if (req.body?.email) {
|
||||
req.body.email = req.body.email?.toLowerCase();
|
||||
}
|
||||
await registrationBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
const validationError = handleValidationError(error, SERVICE_NAME);
|
||||
next(validationError);
|
||||
return;
|
||||
}
|
||||
// Create a new user
|
||||
try {
|
||||
|
||||
// Create a new user
|
||||
const user = req.body;
|
||||
// If superAdmin exists, a token should be attached to all further register requests
|
||||
const superAdminExists = await this.db.checkSuperadmin(req, res);
|
||||
@@ -100,16 +94,14 @@ class AuthController {
|
||||
const html = await this.emailService.buildEmail("welcomeEmailTemplate", {
|
||||
name: newUser.firstName,
|
||||
});
|
||||
this.emailService
|
||||
.sendEmail(newUser.email, "Welcome to Uptime Monitor", html)
|
||||
.catch((error) => {
|
||||
this.logger.warn({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "registerUser",
|
||||
stack: error.stack,
|
||||
});
|
||||
this.emailService.sendEmail(newUser.email, "Welcome to Uptime Monitor", html).catch((error) => {
|
||||
this.logger.warn({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "registerUser",
|
||||
stack: error.stack,
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.warn({
|
||||
message: error.message,
|
||||
@@ -123,10 +115,10 @@ class AuthController {
|
||||
msg: this.stringService.authCreateUser,
|
||||
data: { user: newUser, token: token },
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "registerController"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"registerUser"
|
||||
);
|
||||
|
||||
/**
|
||||
* Logs in a user by validating the user's credentials and issuing a JWT token.
|
||||
@@ -140,18 +132,13 @@ class AuthController {
|
||||
* @returns {Object} The response object with a success status, a message indicating the login of the user, the user data (without password and avatar image), and a JWT token.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or the password is incorrect.
|
||||
*/
|
||||
loginUser = async (req, res, next) => {
|
||||
try {
|
||||
loginUser = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
if (req.body?.email) {
|
||||
req.body.email = req.body.email?.toLowerCase();
|
||||
}
|
||||
await loginValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
const validationError = handleValidationError(error, SERVICE_NAME);
|
||||
next(validationError);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
|
||||
const { email, password } = req.body;
|
||||
|
||||
// Check if user exists
|
||||
@@ -160,10 +147,7 @@ class AuthController {
|
||||
// Compare password
|
||||
const match = await user.comparePassword(password);
|
||||
if (match !== true) {
|
||||
const error = new Error(this.stringService.authIncorrectPassword);
|
||||
error.status = 401;
|
||||
next(error);
|
||||
return;
|
||||
throw createAuthError(this.stringService.authIncorrectPassword);
|
||||
}
|
||||
|
||||
// Remove password from user object. Should this be abstracted to DB layer?
|
||||
@@ -184,11 +168,10 @@ class AuthController {
|
||||
token: token,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
error.status = 401;
|
||||
next(handleError(error, SERVICE_NAME, "loginUser"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"loginUser"
|
||||
);
|
||||
|
||||
/**
|
||||
* Edits a user's information. If the user wants to change their password, the current password is checked before updating to the new password.
|
||||
@@ -204,26 +187,10 @@ class AuthController {
|
||||
* @returns {Object} The response object with a success status, a message indicating the update of the user, and the updated user data.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422), the user is unauthorized (401), or the password is incorrect (403).
|
||||
*/
|
||||
editUser = async (req, res, next) => {
|
||||
try {
|
||||
await editUserParamValidation.validateAsync(req.params);
|
||||
editUser = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await editUserBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
const validationError = handleValidationError(error, SERVICE_NAME);
|
||||
next(validationError);
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO is this neccessary any longer? Verify ownership middleware should handle this
|
||||
if (req.params.userId !== req.user._id.toString()) {
|
||||
const error = new Error(this.stringService.unauthorized);
|
||||
error.status = 401;
|
||||
error.service = SERVICE_NAME;
|
||||
next(error);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Change Password check
|
||||
if (req.body.password && req.body.newPassword) {
|
||||
// Get token from headers
|
||||
@@ -240,24 +207,21 @@ class AuthController {
|
||||
// If not a match, throw a 403
|
||||
// 403 instead of 401 to avoid triggering axios interceptor
|
||||
if (!match) {
|
||||
const error = new Error(this.stringService.authIncorrectPassword);
|
||||
error.status = 403;
|
||||
next(error);
|
||||
return;
|
||||
throw createError(this.stringService.authIncorrectPassword, 403);
|
||||
}
|
||||
// If a match, update the password
|
||||
req.body.password = req.body.newPassword;
|
||||
}
|
||||
|
||||
const updatedUser = await this.db.updateUser(req, res);
|
||||
const updatedUser = await this.db.updateUser({ userId: req?.user?._id, user: req.body, file: req.file });
|
||||
res.success({
|
||||
msg: this.stringService.authUpdateUser,
|
||||
data: updatedUser,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "userEditController"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"editUser"
|
||||
);
|
||||
|
||||
/**
|
||||
* Checks if a superadmin account exists in the database.
|
||||
@@ -268,18 +232,17 @@ class AuthController {
|
||||
* @returns {Object} The response object with a success status, a message indicating the existence of a superadmin, and a boolean indicating the existence of a superadmin.
|
||||
* @throws {Error} If there is an error during the process.
|
||||
*/
|
||||
checkSuperadminExists = async (req, res, next) => {
|
||||
try {
|
||||
checkSuperadminExists = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const superAdminExists = await this.db.checkSuperadmin(req, res);
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.authAdminExists,
|
||||
data: superAdminExists,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "checkSuperadminController"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"checkSuperadminExists"
|
||||
);
|
||||
/**
|
||||
* Requests a recovery token for a user. The user's email is validated and a recovery token is created and sent via email.
|
||||
* @async
|
||||
@@ -291,16 +254,9 @@ class AuthController {
|
||||
* @returns {Object} The response object with a success status, a message indicating the creation of the recovery token, and the message ID of the sent email.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
requestRecovery = async (req, res, next) => {
|
||||
try {
|
||||
requestRecovery = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await recoveryValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
const validationError = handleValidationError(error, SERVICE_NAME);
|
||||
next(validationError);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { email } = req.body;
|
||||
const user = await this.db.getUserByEmail(email);
|
||||
const recoveryToken = await this.db.requestRecoveryToken(req, res);
|
||||
@@ -313,20 +269,16 @@ class AuthController {
|
||||
email,
|
||||
url,
|
||||
});
|
||||
const msgId = await this.emailService.sendEmail(
|
||||
email,
|
||||
"Checkmate Password Reset",
|
||||
html
|
||||
);
|
||||
const msgId = await this.emailService.sendEmail(email, "Checkmate Password Reset", html);
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.authCreateRecoveryToken,
|
||||
data: msgId,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "recoveryRequestController"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"requestRecovery"
|
||||
);
|
||||
/**
|
||||
* Validates a recovery token. The recovery token is validated and if valid, a success message is returned.
|
||||
* @async
|
||||
@@ -338,25 +290,17 @@ class AuthController {
|
||||
* @returns {Object} The response object with a success status and a message indicating the validation of the recovery token.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
validateRecovery = async (req, res, next) => {
|
||||
try {
|
||||
validateRecovery = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await recoveryTokenValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
const validationError = handleValidationError(error, SERVICE_NAME);
|
||||
next(validationError);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.db.validateRecoveryToken(req, res);
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.authVerifyRecoveryToken,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "validateRecoveryTokenController"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"validateRecovery"
|
||||
);
|
||||
|
||||
/**
|
||||
* Resets a user's password. The new password is validated and if valid, the user's password is updated in the database and a new JWT token is issued.
|
||||
@@ -370,27 +314,20 @@ class AuthController {
|
||||
* @returns {Object} The response object with a success status, a message indicating the reset of the password, the updated user data (without password and avatar image), and a new JWT token.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
resetPassword = async (req, res, next) => {
|
||||
try {
|
||||
resetPassword = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await newPasswordValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
const validationError = handleValidationError(error, SERVICE_NAME);
|
||||
next(validationError);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const user = await this.db.resetPassword(req, res);
|
||||
const appSettings = await this.settingsService.getSettings();
|
||||
const token = this.issueToken(user._doc, appSettings);
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.authResetPassword,
|
||||
data: { user, token },
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "resetPasswordController"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"resetPassword"
|
||||
);
|
||||
|
||||
/**
|
||||
* Deletes a user and all associated monitors, checks, and alerts.
|
||||
@@ -401,22 +338,36 @@ class AuthController {
|
||||
* @returns {Object} The response object with success status and message.
|
||||
* @throws {Error} If user validation fails or user is not found in the database.
|
||||
*/
|
||||
deleteUser = async (req, res, next) => {
|
||||
try {
|
||||
const token = getTokenFromHeaders(req.headers);
|
||||
const decodedToken = jwt.decode(token);
|
||||
const { email } = decodedToken;
|
||||
deleteUser = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const email = req?.user?.email;
|
||||
if (!email) {
|
||||
throw new Error("No email in request");
|
||||
}
|
||||
|
||||
const teamId = req?.user?.teamId;
|
||||
const userId = req?.user?._id;
|
||||
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
throw new Error("No user ID in request");
|
||||
}
|
||||
|
||||
const roles = req.user.role;
|
||||
if (roles.includes("demo")) {
|
||||
throw new Error("Demo user cannot be deleted");
|
||||
}
|
||||
|
||||
// Check if the user exists
|
||||
const user = await this.db.getUserByEmail(email);
|
||||
// 1. Find all the monitors associated with the team ID if superadmin
|
||||
|
||||
const result = await this.db.getMonitorsByTeamId({
|
||||
teamId: user.teamId.toString(),
|
||||
teamId: teamId,
|
||||
});
|
||||
|
||||
if (user.role.includes("superadmin")) {
|
||||
//2. Remove all jobs, delete checks and alerts
|
||||
if (roles.includes("superadmin")) {
|
||||
// 2. Remove all jobs, delete checks and alerts
|
||||
result?.monitors.length > 0 &&
|
||||
(await Promise.all(
|
||||
result.monitors.map(async (monitor) => {
|
||||
@@ -425,28 +376,74 @@ class AuthController {
|
||||
));
|
||||
}
|
||||
// 6. Delete the user by id
|
||||
await this.db.deleteUser(user._id);
|
||||
await this.db.deleteUser(userId);
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.authDeleteUser,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteUserController"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"deleteUser"
|
||||
);
|
||||
|
||||
getAllUsers = async (req, res, next) => {
|
||||
try {
|
||||
getAllUsers = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const allUsers = await this.db.getAllUsers(req, res);
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.authGetAllUsers,
|
||||
data: allUsers,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getAllUsersController"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getAllUsers"
|
||||
);
|
||||
|
||||
getUserById = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getUserByIdParamValidation.validateAsync(req.params);
|
||||
const userId = req?.params?.userId;
|
||||
const roles = req?.user?.role;
|
||||
|
||||
if (!userId) {
|
||||
throw new Error("No user ID in request");
|
||||
}
|
||||
|
||||
if (!roles || roles.length === 0) {
|
||||
throw new Error("No roles in request");
|
||||
}
|
||||
|
||||
const user = await this.db.getUserById(roles, userId);
|
||||
|
||||
return res.success({ msg: "ok", data: user });
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getUserById"
|
||||
);
|
||||
|
||||
editUserById = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const roles = req?.user?.role;
|
||||
if (!roles.includes("superadmin")) {
|
||||
throw createError("Unauthorized", 403);
|
||||
}
|
||||
|
||||
const userId = req.params.userId;
|
||||
const user = { ...req.body };
|
||||
|
||||
await editUserByIdParamValidation.validateAsync(req.params);
|
||||
// If this is superadmin self edit, allow "superadmin" role
|
||||
if (userId === req.user._id) {
|
||||
await editSuperadminUserByIdBodyValidation.validateAsync(req.body);
|
||||
} else {
|
||||
await editUserByIdBodyValidation.validateAsync(req.body);
|
||||
}
|
||||
|
||||
await this.db.editUserById(userId, user);
|
||||
return res.success({ msg: "ok" });
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"editUserById"
|
||||
);
|
||||
}
|
||||
|
||||
export default AuthController;
|
||||
@@ -1,6 +1,4 @@
|
||||
import {
|
||||
createCheckParamValidation,
|
||||
createCheckBodyValidation,
|
||||
getChecksParamValidation,
|
||||
getChecksQueryValidation,
|
||||
getTeamChecksParamValidation,
|
||||
@@ -12,9 +10,7 @@ import {
|
||||
ackAllChecksParamValidation,
|
||||
ackAllChecksBodyValidation,
|
||||
} from "../validation/joi.js";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { getTokenFromHeaders } from "../utils/utils.js";
|
||||
import { handleValidationError, handleError } from "./controllerUtils.js";
|
||||
import { asyncHandler } from "../utils/errorUtils.js";
|
||||
|
||||
const SERVICE_NAME = "checkController";
|
||||
|
||||
@@ -25,41 +21,41 @@ class CheckController {
|
||||
this.stringService = stringService;
|
||||
}
|
||||
|
||||
createCheck = async (req, res, next) => {
|
||||
try {
|
||||
await createCheckParamValidation.validateAsync(req.params);
|
||||
await createCheckBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const checkData = { ...req.body };
|
||||
const check = await this.db.createCheck(checkData);
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.checkCreate,
|
||||
data: check,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "createCheck"));
|
||||
}
|
||||
};
|
||||
|
||||
getChecksByMonitor = async (req, res, next) => {
|
||||
try {
|
||||
getChecksByMonitor = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getChecksParamValidation.validateAsync(req.params);
|
||||
await getChecksQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { monitorId } = req.params;
|
||||
let { type, sortOrder, dateRange, filter, ack, page, rowsPerPage, status } =
|
||||
req.query;
|
||||
const monitorId = req?.params?.monitorId;
|
||||
|
||||
if (!monitorId) {
|
||||
throw new Error("No monitor ID in request");
|
||||
}
|
||||
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
const monitor = await this.db.getMonitorById(monitorId);
|
||||
|
||||
if (!monitor) {
|
||||
const err = new Error("Monitor not found");
|
||||
err.status = 404;
|
||||
err.service = SERVICE_NAME;
|
||||
err.method = "getChecksByMonitor";
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (!monitor.teamId.equals(teamId)) {
|
||||
const err = new Error("Unauthorized");
|
||||
err.status = 403;
|
||||
err.service = SERVICE_NAME;
|
||||
err.method = "getChecksByMonitor";
|
||||
throw err;
|
||||
}
|
||||
|
||||
let { type, sortOrder, dateRange, filter, ack, page, rowsPerPage, status } = req.query;
|
||||
const result = await this.db.getChecksByMonitor({
|
||||
monitorId,
|
||||
type,
|
||||
@@ -76,22 +72,22 @@ class CheckController {
|
||||
msg: this.stringService.checkGet,
|
||||
data: result,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getChecks"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getChecksByMonitor"
|
||||
);
|
||||
|
||||
getChecksByTeam = async (req, res, next) => {
|
||||
try {
|
||||
getChecksByTeam = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getTeamChecksParamValidation.validateAsync(req.params);
|
||||
await getTeamChecksQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
|
||||
let { sortOrder, dateRange, filter, ack, page, rowsPerPage } = req.query;
|
||||
const { teamId } = req.user;
|
||||
const teamId = req?.user?.teamId;
|
||||
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
const checkData = await this.db.getChecksByTeam({
|
||||
sortOrder,
|
||||
@@ -106,36 +102,44 @@ class CheckController {
|
||||
msg: this.stringService.checkGet,
|
||||
data: checkData,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getTeamChecks"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getChecksByTeam"
|
||||
);
|
||||
|
||||
getChecksSummaryByTeamId = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const teamId = req?.user?.teamId;
|
||||
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
getChecksSummaryByTeamId = async (req, res, next) => {
|
||||
try {
|
||||
const { teamId } = req.user;
|
||||
const summary = await this.db.getChecksSummaryByTeamId({ teamId });
|
||||
return res.success({
|
||||
msg: this.stringService.checkGetSummary,
|
||||
data: summary,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getChecksSummaryByTeamId"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getChecksSummaryByTeamId"
|
||||
);
|
||||
|
||||
ackCheck = async (req, res, next) => {
|
||||
try {
|
||||
ackCheck = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await ackCheckBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { checkId } = req.params;
|
||||
const { ack } = req.body;
|
||||
const { teamId } = req.user;
|
||||
const checkId = req?.params?.checkId;
|
||||
const ack = req?.body?.ack;
|
||||
const teamId = req?.user?.teamId;
|
||||
|
||||
if (!checkId) {
|
||||
throw new Error("No check ID in request");
|
||||
}
|
||||
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
const updatedCheck = await this.db.ackCheck(checkId, teamId, ack);
|
||||
|
||||
@@ -143,24 +147,45 @@ class CheckController {
|
||||
msg: this.stringService.checkUpdateStatus,
|
||||
data: updatedCheck,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "ackCheck"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"ackCheck"
|
||||
);
|
||||
|
||||
ackAllChecks = async (req, res, next) => {
|
||||
try {
|
||||
ackAllChecks = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await ackAllChecksParamValidation.validateAsync(req.params);
|
||||
await ackAllChecksBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { monitorId, path } = req.params;
|
||||
const { ack } = req.body;
|
||||
const { teamId } = req.user;
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
const monitorId = req?.params?.monitorId;
|
||||
|
||||
const path = req?.params?.path;
|
||||
|
||||
const ack = req?.body?.ack;
|
||||
|
||||
if (path === "monitor") {
|
||||
if (!monitorId) {
|
||||
throw new Error("No monitor ID in request");
|
||||
}
|
||||
|
||||
const monitor = await this.db.getMonitorById(monitorId);
|
||||
if (!monitor) {
|
||||
throw new Error("Monitor not found");
|
||||
}
|
||||
|
||||
if (!monitor.teamId.equals(teamId)) {
|
||||
const err = new Error("Unauthorized");
|
||||
err.status = 403;
|
||||
err.service = SERVICE_NAME;
|
||||
err.method = "ackAllChecks";
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const updatedChecks = await this.db.ackAllChecks(monitorId, teamId, ack, path);
|
||||
|
||||
@@ -168,64 +193,81 @@ class CheckController {
|
||||
msg: this.stringService.checkUpdateStatus,
|
||||
data: updatedChecks,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "ackAllChecks"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"ackAllChecks"
|
||||
);
|
||||
|
||||
deleteChecks = async (req, res, next) => {
|
||||
try {
|
||||
deleteChecks = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await deleteChecksParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const monitorId = req?.params?.monitorId;
|
||||
const teamId = req?.user?.teamId;
|
||||
|
||||
if (!monitorId) {
|
||||
throw new Error("No monitor ID in request");
|
||||
}
|
||||
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
const monitor = await this.db.getMonitorById(monitorId);
|
||||
|
||||
if (!monitor) {
|
||||
const err = new Error("Monitor not found");
|
||||
err.status = 404;
|
||||
err.service = SERVICE_NAME;
|
||||
err.method = "deleteChecks";
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (!monitor.teamId.equals(teamId)) {
|
||||
const err = new Error("Unauthorized");
|
||||
err.status = 403;
|
||||
err.service = SERVICE_NAME;
|
||||
err.method = "deleteChecks";
|
||||
throw err;
|
||||
}
|
||||
|
||||
const deletedCount = await this.db.deleteChecks(req.params.monitorId);
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.checkDelete,
|
||||
data: { deletedCount },
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteChecks"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"deleteChecks"
|
||||
);
|
||||
|
||||
deleteChecksByTeamId = async (req, res, next) => {
|
||||
try {
|
||||
deleteChecksByTeamId = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await deleteChecksByTeamIdParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { teamId } = req.user;
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
const deletedCount = await this.db.deleteChecksByTeamId(teamId);
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.checkDelete,
|
||||
data: { deletedCount },
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteChecksByTeamId"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"deleteChecksByTeamId"
|
||||
);
|
||||
|
||||
updateChecksTTL = async (req, res, next) => {
|
||||
const SECONDS_PER_DAY = 86400;
|
||||
updateChecksTTL = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const SECONDS_PER_DAY = 86400;
|
||||
|
||||
try {
|
||||
await updateChecksTTLBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Get user's teamId
|
||||
const { teamId } = req.user;
|
||||
const ttl = parseInt(req.body.ttl, 10) * SECONDS_PER_DAY;
|
||||
await this.db.updateChecksTTL(teamId, ttl);
|
||||
@@ -233,9 +275,9 @@ class CheckController {
|
||||
return res.success({
|
||||
msg: this.stringService.checkUpdateTTL,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "updateTTL"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"updateChecksTtl"
|
||||
);
|
||||
}
|
||||
export default CheckController;
|
||||
@@ -1,16 +1,4 @@
|
||||
const handleValidationError = (error, serviceName) => {
|
||||
error.status = 422;
|
||||
error.service = serviceName;
|
||||
error.message = error.details?.[0]?.message || error.message || "Validation Error";
|
||||
return error;
|
||||
};
|
||||
|
||||
const handleError = (error, serviceName, method, status = 500) => {
|
||||
error.status === undefined ? (error.status = status) : null;
|
||||
error.service === undefined ? (error.service = serviceName) : null;
|
||||
error.method === undefined ? (error.method = method) : null;
|
||||
return error;
|
||||
};
|
||||
import { createServerError } from "../utils/errorUtils.js";
|
||||
|
||||
const fetchMonitorCertificate = async (sslChecker, monitor) => {
|
||||
const monitorUrl = new URL(monitor.url);
|
||||
@@ -18,9 +6,9 @@ const fetchMonitorCertificate = async (sslChecker, monitor) => {
|
||||
const cert = await sslChecker(hostname);
|
||||
// Throw an error if no cert or if cert.validTo is not present
|
||||
if (cert?.validTo === null || cert?.validTo === undefined) {
|
||||
throw new Error("Certificate not found");
|
||||
throw createServerError("Certificate not found");
|
||||
}
|
||||
return cert;
|
||||
};
|
||||
|
||||
export { handleValidationError, handleError, fetchMonitorCertificate };
|
||||
export { fetchMonitorCertificate };
|
||||
@@ -1,48 +1,91 @@
|
||||
import { handleError } from "./controllerUtils.js";
|
||||
import v8 from "v8";
|
||||
import os from "os";
|
||||
import { asyncHandler } from "../utils/errorUtils.js";
|
||||
|
||||
const SERVICE_NAME = "diagnosticController";
|
||||
|
||||
const obs = new PerformanceObserver((items) => {
|
||||
const entry = items.getEntries()[0];
|
||||
performance.clearMarks();
|
||||
});
|
||||
obs.observe({ entryTypes: ["measure"] });
|
||||
class DiagnosticController {
|
||||
constructor(db) {
|
||||
this.db = db;
|
||||
this.getMonitorsByTeamIdExecutionStats =
|
||||
this.getMonitorsByTeamIdExecutionStats.bind(this);
|
||||
this.getDbStats = this.getDbStats.bind(this);
|
||||
}
|
||||
|
||||
async getMonitorsByTeamIdExecutionStats(req, res, next) {
|
||||
try {
|
||||
const data = await this.db.getMonitorsByTeamIdExecutionStats(req);
|
||||
return res.success({
|
||||
msg: "OK",
|
||||
data,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMonitorsByTeamIdExecutionStats"));
|
||||
}
|
||||
}
|
||||
getCPUUsage = async () => {
|
||||
const startUsage = process.cpuUsage();
|
||||
const timingPeriod = 1000; // measured in ms
|
||||
await new Promise((resolve) => setTimeout(resolve, timingPeriod));
|
||||
const endUsage = process.cpuUsage(startUsage);
|
||||
const cpuUsage = {
|
||||
userUsageMs: endUsage.user / 1000,
|
||||
systemUsageMs: endUsage.system / 1000,
|
||||
usagePercentage: ((endUsage.user + endUsage.system) / 1000 / timingPeriod) * 100,
|
||||
};
|
||||
return cpuUsage;
|
||||
};
|
||||
|
||||
async getDbStats(req, res, next) {
|
||||
try {
|
||||
const { methodName, args = [] } = req.body;
|
||||
if (!methodName || !this.db[methodName]) {
|
||||
return res.error({
|
||||
msg: "Invalid method name or method doesn't exist",
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
const explainMethod = await this.db[methodName].apply(this.db, args);
|
||||
const stats = {
|
||||
methodName,
|
||||
timestamp: new Date(),
|
||||
explain: explainMethod,
|
||||
getSystemStats = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
// Memory Usage
|
||||
const totalMemory = os.totalmem();
|
||||
const freeMemory = os.freemem();
|
||||
|
||||
const osStats = {
|
||||
freeMemoryBytes: freeMemory, // bytes
|
||||
totalMemoryBytes: totalMemory, // bytes
|
||||
};
|
||||
|
||||
const used = process.memoryUsage();
|
||||
const memoryUsage = {};
|
||||
for (let key in used) {
|
||||
memoryUsage[`${key}Mb`] = Math.round((used[key] / 1024 / 1024) * 100) / 100; // MB
|
||||
}
|
||||
|
||||
// CPU Usage
|
||||
const cpuMetrics = await this.getCPUUsage();
|
||||
|
||||
// V8 Heap Statistics
|
||||
const heapStats = v8.getHeapStatistics();
|
||||
const v8Metrics = {
|
||||
totalHeapSizeBytes: heapStats.total_heap_size, // bytes
|
||||
usedHeapSizeBytes: heapStats.used_heap_size, // bytes
|
||||
heapSizeLimitBytes: heapStats.heap_size_limit, // bytes
|
||||
};
|
||||
|
||||
// Event Loop Delay
|
||||
let eventLoopDelay = 0;
|
||||
performance.mark("start");
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
performance.mark("end");
|
||||
performance.measure("eventLoopDelay", "start", "end");
|
||||
const entries = performance.getEntriesByName("eventLoopDelay");
|
||||
if (entries.length > 0) {
|
||||
eventLoopDelay = entries[0].duration;
|
||||
}
|
||||
|
||||
// Uptime
|
||||
const uptimeMs = process.uptime() * 1000; // ms
|
||||
|
||||
// Combine Metrics
|
||||
const diagnostics = {
|
||||
osStats,
|
||||
memoryUsage,
|
||||
cpuUsage: cpuMetrics,
|
||||
v8HeapStats: v8Metrics,
|
||||
eventLoopDelayMs: eventLoopDelay,
|
||||
uptimeMs,
|
||||
};
|
||||
|
||||
return res.success({
|
||||
msg: "OK",
|
||||
data: stats,
|
||||
data: diagnostics,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getDbStats"));
|
||||
}
|
||||
}
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getSystemStats"
|
||||
);
|
||||
}
|
||||
export default DiagnosticController;
|
||||
@@ -1,12 +1,7 @@
|
||||
import {
|
||||
inviteRoleValidation,
|
||||
inviteBodyValidation,
|
||||
inviteVerificationBodyValidation,
|
||||
} from "../validation/joi.js";
|
||||
import logger from "../utils/logger.js";
|
||||
import { inviteRoleValidation, inviteBodyValidation, inviteVerificationBodyValidation } from "../validation/joi.js";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { handleError, handleValidationError } from "./controllerUtils.js";
|
||||
import { getTokenFromHeaders } from "../utils/utils.js";
|
||||
import { asyncHandler, createServerError } from "../utils/errorUtils.js";
|
||||
|
||||
const SERVICE_NAME = "inviteController";
|
||||
|
||||
@@ -31,99 +26,67 @@ class InviteController {
|
||||
* @returns {Object} The response object with a success status, a message indicating the sending of the invitation, and the invitation token.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
getInviteToken = async (req, res, next) => {
|
||||
try {
|
||||
getInviteToken = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
// Only admins can invite
|
||||
const token = getTokenFromHeaders(req.headers);
|
||||
const { role, teamId } = jwt.decode(token);
|
||||
req.body.teamId = teamId;
|
||||
try {
|
||||
await inviteRoleValidation.validateAsync({ roles: role });
|
||||
await inviteBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
await inviteRoleValidation.validateAsync({ roles: role });
|
||||
await inviteBodyValidation.validateAsync(req.body);
|
||||
|
||||
const inviteToken = await this.db.requestInviteToken({ ...req.body });
|
||||
return res.success({
|
||||
msg: this.stringService.inviteIssued,
|
||||
data: inviteToken,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "inviteController"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getInviteToken"
|
||||
);
|
||||
|
||||
sendInviteEmail = async (req, res, next) => {
|
||||
try {
|
||||
sendInviteEmail = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
// Only admins can invite
|
||||
const token = getTokenFromHeaders(req.headers);
|
||||
const { role, firstname, teamId } = jwt.decode(token);
|
||||
req.body.teamId = teamId;
|
||||
try {
|
||||
await inviteRoleValidation.validateAsync({ roles: role });
|
||||
await inviteBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
await inviteRoleValidation.validateAsync({ roles: role });
|
||||
await inviteBodyValidation.validateAsync(req.body);
|
||||
|
||||
const inviteToken = await this.db.requestInviteToken({ ...req.body });
|
||||
const { clientHost } = this.settingsService.getSettings();
|
||||
|
||||
try {
|
||||
const html = await this.emailService.buildEmail("employeeActivationTemplate", {
|
||||
name: firstname,
|
||||
link: `${clientHost}/register/${inviteToken.token}`,
|
||||
});
|
||||
const result = await this.emailService.sendEmail(
|
||||
req.body.email,
|
||||
"Welcome to Uptime Monitor",
|
||||
html
|
||||
);
|
||||
if (!result) {
|
||||
return res.error({
|
||||
msg: "Failed to send invite e-mail... Please verify your settings.",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "sendInviteEmail",
|
||||
stack: error.stack,
|
||||
});
|
||||
const html = await this.emailService.buildEmail("employeeActivationTemplate", {
|
||||
name: firstname,
|
||||
link: `${clientHost}/register/${inviteToken.token}`,
|
||||
});
|
||||
const result = await this.emailService.sendEmail(req.body.email, "Welcome to Uptime Monitor", html);
|
||||
if (!result) {
|
||||
throw createServerError("Failed to send invite e-mail... Please verify your settings.");
|
||||
}
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.inviteIssued,
|
||||
data: inviteToken,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "inviteController"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"sendInviteEmail"
|
||||
);
|
||||
|
||||
inviteVerifyController = async (req, res, next) => {
|
||||
try {
|
||||
inviteVerifyController = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await inviteVerificationBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const invite = await this.db.getInviteToken(req.body.token);
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.inviteVerified,
|
||||
data: invite,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "inviteVerifyController"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"inviteVerifyController"
|
||||
);
|
||||
}
|
||||
|
||||
export default InviteController;
|
||||
@@ -1,23 +1,22 @@
|
||||
import { handleError } from "./controllerUtils.js";
|
||||
import { asyncHandler } from "../utils/errorUtils.js";
|
||||
|
||||
const SERVICE_NAME = "JobQueueController";
|
||||
const SERVICE_NAME = "LogController";
|
||||
|
||||
class LogController {
|
||||
constructor(logger) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
getLogs = async (req, res, next) => {
|
||||
try {
|
||||
getLogs = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const logs = await this.logger.getLogs();
|
||||
res.success({
|
||||
msg: "Logs fetched successfully",
|
||||
data: logs,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getLogs"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getLogs"
|
||||
);
|
||||
}
|
||||
export default LogController;
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
getMaintenanceWindowsByTeamIdQueryValidation,
|
||||
deleteMaintenanceWindowByIdParamValidation,
|
||||
} from "../validation/joi.js";
|
||||
import { handleValidationError, handleError } from "./controllerUtils.js";
|
||||
import { asyncHandler } from "../utils/errorUtils.js";
|
||||
|
||||
const SERVICE_NAME = "maintenanceWindowController";
|
||||
|
||||
@@ -18,16 +18,29 @@ class MaintenanceWindowController {
|
||||
this.stringService = stringService;
|
||||
}
|
||||
|
||||
createMaintenanceWindows = async (req, res, next) => {
|
||||
try {
|
||||
createMaintenanceWindows = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await createMaintenanceWindowBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { teamId } = req.user;
|
||||
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("Team ID is required");
|
||||
}
|
||||
|
||||
const monitorIds = req.body.monitors;
|
||||
|
||||
const monitors = await this.db.getMonitorsByIds(monitorIds);
|
||||
|
||||
const unauthorizedMonitors = monitors.filter((monitor) => !monitor.teamId.equals(teamId));
|
||||
|
||||
if (unauthorizedMonitors.length > 0) {
|
||||
const error = new Error("Unauthorized access to one or more monitors");
|
||||
error.status = 403;
|
||||
error.service = SERVICE_NAME;
|
||||
error.method = "createMaintenanceWindows";
|
||||
throw error;
|
||||
}
|
||||
|
||||
const dbTransactions = monitorIds.map((monitorId) => {
|
||||
return this.db.createMaintenanceWindow({
|
||||
teamId,
|
||||
@@ -44,114 +57,111 @@ class MaintenanceWindowController {
|
||||
return res.success({
|
||||
msg: this.stringService.maintenanceWindowCreate,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "createMaintenanceWindow"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"createMaintenanceWindows"
|
||||
);
|
||||
|
||||
getMaintenanceWindowById = async (req, res, next) => {
|
||||
try {
|
||||
getMaintenanceWindowById = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const maintenanceWindow = await this.db.getMaintenanceWindowById(req.params.id);
|
||||
|
||||
const teamId = req.user.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("Team ID is required");
|
||||
}
|
||||
|
||||
const maintenanceWindow = await this.db.getMaintenanceWindowById({ id: req.params.id, teamId });
|
||||
return res.success({
|
||||
msg: this.stringService.maintenanceWindowGetById,
|
||||
data: maintenanceWindow,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowById"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getMaintenanceWindowById"
|
||||
);
|
||||
|
||||
getMaintenanceWindowsByTeamId = async (req, res, next) => {
|
||||
try {
|
||||
getMaintenanceWindowsByTeamId = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { teamId } = req.user;
|
||||
const maintenanceWindows = await this.db.getMaintenanceWindowsByTeamId(
|
||||
teamId,
|
||||
req.query
|
||||
);
|
||||
const teamId = req?.user?.teamId;
|
||||
|
||||
if (!teamId) {
|
||||
throw new Error("Team ID is required");
|
||||
}
|
||||
|
||||
const maintenanceWindows = await this.db.getMaintenanceWindowsByTeamId(teamId, req.query);
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.maintenanceWindowGetByTeam,
|
||||
data: maintenanceWindows,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByUserId"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getMaintenanceWindowsByTeamId"
|
||||
);
|
||||
|
||||
getMaintenanceWindowsByMonitorId = async (req, res, next) => {
|
||||
try {
|
||||
getMaintenanceWindowsByMonitorId = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const maintenanceWindows = await this.db.getMaintenanceWindowsByMonitorId(
|
||||
req.params.monitorId
|
||||
);
|
||||
const monitorId = req.params.monitorId;
|
||||
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("Team ID is required");
|
||||
}
|
||||
|
||||
const maintenanceWindows = await this.db.getMaintenanceWindowsByMonitorId({ monitorId, teamId });
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.maintenanceWindowGetByUser,
|
||||
data: maintenanceWindows,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByMonitorId"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getMaintenanceWindowsByMonitorId"
|
||||
);
|
||||
|
||||
deleteMaintenanceWindow = async (req, res, next) => {
|
||||
try {
|
||||
deleteMaintenanceWindow = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await this.db.deleteMaintenanceWindowById(req.params.id);
|
||||
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("Team ID is required");
|
||||
}
|
||||
|
||||
await this.db.deleteMaintenanceWindowById({ id: req.params.id, teamId });
|
||||
return res.success({
|
||||
msg: this.stringService.maintenanceWindowDelete,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteMaintenanceWindow"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"deleteMaintenanceWindow"
|
||||
);
|
||||
|
||||
editMaintenanceWindow = async (req, res, next) => {
|
||||
try {
|
||||
editMaintenanceWindow = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await editMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
||||
await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const editedMaintenanceWindow = await this.db.editMaintenanceWindowById(
|
||||
req.params.id,
|
||||
req.body
|
||||
);
|
||||
|
||||
const teamId = req.user.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("Team ID is required");
|
||||
}
|
||||
|
||||
const editedMaintenanceWindow = await this.db.editMaintenanceWindowById({ id: req.params.id, body: req.body, teamId });
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.maintenanceWindowEdit,
|
||||
data: editedMaintenanceWindow,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "editMaintenanceWindow"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"editMaintenanceWindow"
|
||||
);
|
||||
}
|
||||
|
||||
export default MaintenanceWindowController;
|
||||
@@ -16,12 +16,13 @@ import {
|
||||
} from "../validation/joi.js";
|
||||
import sslChecker from "ssl-checker";
|
||||
import logger from "../utils/logger.js";
|
||||
import { handleError, handleValidationError } from "./controllerUtils.js";
|
||||
import axios from "axios";
|
||||
import seedDb from "../db/mongo/utils/seedDb.js";
|
||||
const SERVICE_NAME = "monitorController";
|
||||
import pkg from "papaparse";
|
||||
import { asyncHandler, createServerError } from "../utils/errorUtils.js";
|
||||
import { fetchMonitorCertificate } from "./controllerUtils.js";
|
||||
|
||||
const SERVICE_NAME = "monitorController";
|
||||
class MonitorController {
|
||||
constructor(db, settingsService, jobQueue, stringService, emailService) {
|
||||
this.db = db;
|
||||
@@ -31,6 +32,15 @@ class MonitorController {
|
||||
this.emailService = emailService;
|
||||
}
|
||||
|
||||
async verifyTeamAccess(teamId, monitorId) {
|
||||
const monitor = await this.db.getMonitorById(monitorId);
|
||||
if (!monitor.teamId.equals(teamId)) {
|
||||
const error = new Error("Unauthorized");
|
||||
error.status = 403;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all monitors
|
||||
* @async
|
||||
@@ -40,44 +50,30 @@ class MonitorController {
|
||||
* @returns {Promise<Express.Response>}
|
||||
* @throws {Error}
|
||||
*/
|
||||
getAllMonitors = async (req, res, next) => {
|
||||
try {
|
||||
getAllMonitors = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const monitors = await this.db.getAllMonitors();
|
||||
return res.success({
|
||||
msg: this.stringService.monitorGetAll,
|
||||
data: monitors,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getAllMonitors"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getAllMonitors"
|
||||
);
|
||||
|
||||
/**
|
||||
* Returns all monitors with uptime stats for 1,7,30, and 90 days
|
||||
* @async
|
||||
* @param {Express.Request} req
|
||||
* @param {Express.Response} res
|
||||
* @param {function} next
|
||||
* @returns {Promise<Express.Response>}
|
||||
* @throws {Error}
|
||||
*/
|
||||
getAllMonitorsWithUptimeStats = async (req, res, next) => {
|
||||
try {
|
||||
const monitors = await this.db.getAllMonitorsWithUptimeStats();
|
||||
return res.success({
|
||||
msg: this.stringService.monitorGetAll,
|
||||
data: monitors,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getAllMonitorsWithUptimeStats"));
|
||||
}
|
||||
};
|
||||
|
||||
getUptimeDetailsById = async (req, res, next) => {
|
||||
try {
|
||||
getUptimeDetailsById = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const { monitorId } = req.params;
|
||||
const { dateRange, normalize } = req.query;
|
||||
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("Team ID is required");
|
||||
}
|
||||
|
||||
await this.verifyTeamAccess(teamId, monitorId);
|
||||
|
||||
const data = await this.db.getUptimeDetailsById({
|
||||
monitorId,
|
||||
dateRange,
|
||||
@@ -87,10 +83,10 @@ class MonitorController {
|
||||
msg: this.stringService.monitorGetByIdSuccess,
|
||||
data,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMonitorDetailsById"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getUptimeDetailsById"
|
||||
);
|
||||
|
||||
/**
|
||||
* Returns monitor stats for monitor with matching ID
|
||||
@@ -101,19 +97,21 @@ class MonitorController {
|
||||
* @returns {Promise<Express.Response>}
|
||||
* @throws {Error}
|
||||
*/
|
||||
getMonitorStatsById = async (req, res, next) => {
|
||||
try {
|
||||
getMonitorStatsById = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getMonitorStatsByIdParamValidation.validateAsync(req.params);
|
||||
await getMonitorStatsByIdQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
let { limit, sortOrder, dateRange, numToDisplay, normalize } = req.query;
|
||||
const { monitorId } = req.params;
|
||||
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("Team ID is required");
|
||||
}
|
||||
|
||||
await this.verifyTeamAccess(teamId, monitorId);
|
||||
|
||||
const monitorStats = await this.db.getMonitorStatsById({
|
||||
monitorId,
|
||||
limit,
|
||||
@@ -126,10 +124,10 @@ class MonitorController {
|
||||
msg: this.stringService.monitorStatsById,
|
||||
data: monitorStats,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMonitorStatsById"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getMonitorStatsById"
|
||||
);
|
||||
|
||||
/**
|
||||
* Get hardware details for a specific monitor by ID
|
||||
@@ -140,35 +138,33 @@ class MonitorController {
|
||||
* @returns {Promise<Express.Response>}
|
||||
* @throws {Error} - Throws error if monitor not found or other database errors
|
||||
*/
|
||||
getHardwareDetailsById = async (req, res, next) => {
|
||||
try {
|
||||
getHardwareDetailsById = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getHardwareDetailsByIdParamValidation.validateAsync(req.params);
|
||||
await getHardwareDetailsByIdQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { monitorId } = req.params;
|
||||
const { dateRange } = req.query;
|
||||
|
||||
const monitorId = req?.params?.monitorId;
|
||||
const dateRange = req?.query?.dateRange;
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("Team ID is required");
|
||||
}
|
||||
|
||||
await this.verifyTeamAccess(teamId, monitorId);
|
||||
const monitor = await this.db.getHardwareDetailsById({ monitorId, dateRange });
|
||||
return res.success({
|
||||
msg: this.stringService.monitorGetByIdSuccess,
|
||||
data: monitor,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getHardwareDetailsById"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getHardwareDetailsById"
|
||||
);
|
||||
|
||||
getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) => {
|
||||
try {
|
||||
getMonitorCertificate = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getCertificateParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
}
|
||||
|
||||
try {
|
||||
const { monitorId } = req.params;
|
||||
const monitor = await this.db.getMonitorById(monitorId);
|
||||
const certificate = await fetchMonitorCertificate(sslChecker, monitor);
|
||||
@@ -179,10 +175,10 @@ class MonitorController {
|
||||
certificateDate: new Date(certificate.validTo),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMonitorCertificate"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getMonitorCertificate"
|
||||
);
|
||||
|
||||
/**
|
||||
* Retrieves a monitor by its ID.
|
||||
@@ -195,25 +191,32 @@ class MonitorController {
|
||||
* @returns {Object} The response object with a success status, a message, and the retrieved monitor data.
|
||||
* @throws {Error} If there is an error during the process, especially if the monitor is not found (404) or if there is a validation error (422).
|
||||
*/
|
||||
getMonitorById = async (req, res, next) => {
|
||||
try {
|
||||
getMonitorById = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getMonitorByIdParamValidation.validateAsync(req.params);
|
||||
await getMonitorByIdQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const monitor = await this.db.getMonitorById(req.params.monitorId);
|
||||
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("Team ID is required");
|
||||
}
|
||||
|
||||
if (!monitor.teamId.equals(teamId)) {
|
||||
const error = new Error("Unauthorized");
|
||||
error.status = 403;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.monitorGetByIdSuccess,
|
||||
data: monitor,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMonitorById"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getMonitorById"
|
||||
);
|
||||
|
||||
/**
|
||||
* Creates a new monitor and adds it to the job queue.
|
||||
@@ -226,15 +229,10 @@ class MonitorController {
|
||||
* @returns {Object} The response object with a success status, a message indicating the creation of the monitor, and the created monitor data.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
createMonitor = async (req, res, next) => {
|
||||
try {
|
||||
createMonitor = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await createMonitorBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { _id, teamId } = req.user;
|
||||
const monitor = await this.db.createMonitor({
|
||||
body: req.body,
|
||||
@@ -248,10 +246,10 @@ class MonitorController {
|
||||
msg: this.stringService.monitorCreate,
|
||||
data: monitor,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "createMonitor"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"createMonitor"
|
||||
);
|
||||
|
||||
/**
|
||||
* Creates bulk monitors and adds them to the job queue after parsing CSV.
|
||||
@@ -263,8 +261,8 @@ class MonitorController {
|
||||
* @returns {Object} The response object with a success status and message.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
createBulkMonitors = async (req, res, next) => {
|
||||
try {
|
||||
createBulkMonitors = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const { parse } = pkg;
|
||||
|
||||
// validate the file
|
||||
@@ -310,51 +308,43 @@ class MonitorController {
|
||||
return value;
|
||||
},
|
||||
complete: async ({ data, errors }) => {
|
||||
try {
|
||||
if (errors.length > 0) {
|
||||
throw new Error("Error parsing CSV");
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
throw new Error("CSV file contains no data rows");
|
||||
}
|
||||
|
||||
const enrichedData = data.map((monitor) => ({
|
||||
userId: _id,
|
||||
teamId,
|
||||
...monitor,
|
||||
description: monitor.description || monitor.name || monitor.url,
|
||||
name: monitor.name || monitor.url,
|
||||
type: monitor.type || "http",
|
||||
}));
|
||||
|
||||
await createMonitorsBodyValidation.validateAsync(enrichedData);
|
||||
|
||||
try {
|
||||
const monitors = await this.db.createBulkMonitors(enrichedData);
|
||||
|
||||
await Promise.all(
|
||||
monitors.map(async (monitor, index) => {
|
||||
this.jobQueue.addJob(monitor._id, monitor);
|
||||
})
|
||||
);
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.bulkMonitorsCreate,
|
||||
data: monitors,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "createBulkMonitors"));
|
||||
}
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "createBulkMonitors"));
|
||||
if (errors.length > 0) {
|
||||
throw createServerError("Error parsing CSV");
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
throw createServerError("CSV file contains no data rows");
|
||||
}
|
||||
|
||||
const enrichedData = data.map((monitor) => ({
|
||||
userId: _id,
|
||||
teamId,
|
||||
...monitor,
|
||||
description: monitor.description || monitor.name || monitor.url,
|
||||
name: monitor.name || monitor.url,
|
||||
type: monitor.type || "http",
|
||||
}));
|
||||
|
||||
await createMonitorsBodyValidation.validateAsync(enrichedData);
|
||||
|
||||
const monitors = await this.db.createBulkMonitors(enrichedData);
|
||||
|
||||
await Promise.all(
|
||||
monitors.map(async (monitor, index) => {
|
||||
this.jobQueue.addJob(monitor._id, monitor);
|
||||
})
|
||||
);
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.bulkMonitorsCreate,
|
||||
data: monitors,
|
||||
});
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return next(handleError(error, SERVICE_NAME, "createBulkMonitors"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"createBulkMonitors"
|
||||
);
|
||||
/**
|
||||
* Checks if the endpoint can be resolved
|
||||
* @async
|
||||
@@ -365,15 +355,9 @@ class MonitorController {
|
||||
* @returns {Object} The response object with a success status, a message, and the resolution result.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
checkEndpointResolution = async (req, res, next) => {
|
||||
try {
|
||||
checkEndpointResolution = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getMonitorURLByQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { monitorURL } = req.query;
|
||||
const parsedUrl = new URL(monitorURL);
|
||||
const response = await axios.get(parsedUrl, {
|
||||
@@ -384,10 +368,10 @@ class MonitorController {
|
||||
status: response.status,
|
||||
msg: response.statusText,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "checkEndpointResolution"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"checkEndpointResolution"
|
||||
);
|
||||
|
||||
/**
|
||||
* Deletes a monitor by its ID and also deletes associated checks, alerts, and notifications.
|
||||
@@ -400,24 +384,25 @@ class MonitorController {
|
||||
* @returns {Object} The response object with a success status and a message indicating the deletion of the monitor.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or an error in deleting associated records.
|
||||
*/
|
||||
deleteMonitor = async (req, res, next) => {
|
||||
try {
|
||||
deleteMonitor = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getMonitorByIdParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const monitorId = req.params.monitorId;
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("Team ID is required");
|
||||
}
|
||||
|
||||
await this.verifyTeamAccess(teamId, monitorId);
|
||||
|
||||
const monitor = await this.db.deleteMonitor({ monitorId });
|
||||
await this.jobQueue.deleteJob(monitor);
|
||||
await this.db.deleteStatusPagesByMonitorId(monitor._id);
|
||||
return res.success({ msg: this.stringService.monitorDelete });
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteMonitor"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"deleteMonitor"
|
||||
);
|
||||
|
||||
/**
|
||||
* Deletes all monitors associated with a team.
|
||||
@@ -430,9 +415,9 @@ class MonitorController {
|
||||
* @returns {Object} The response object with a success status and a message indicating the number of deleted monitors.
|
||||
* @throws {Error} If there is an error during the deletion process.
|
||||
*/
|
||||
deleteAllMonitors = async (req, res, next) => {
|
||||
try {
|
||||
const { teamId } = req.user;
|
||||
deleteAllMonitors = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const teamId = req?.user?.teamId;
|
||||
const { monitors, deletedCount } = await this.db.deleteAllMonitors(teamId);
|
||||
await Promise.all(
|
||||
monitors.map(async (monitor) => {
|
||||
@@ -442,7 +427,7 @@ class MonitorController {
|
||||
await this.db.deletePageSpeedChecksByMonitorId(monitor._id);
|
||||
await this.db.deleteNotificationsByMonitorId(monitor._id);
|
||||
} catch (error) {
|
||||
logger.error({
|
||||
logger.warn({
|
||||
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "deleteAllMonitors",
|
||||
@@ -452,10 +437,10 @@ class MonitorController {
|
||||
})
|
||||
);
|
||||
return res.success({ msg: `Deleted ${deletedCount} monitors` });
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteAllMonitors"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"deleteAllMonitors"
|
||||
);
|
||||
|
||||
/**
|
||||
* Edits a monitor by its ID, updates its notifications, and updates its job in the job queue.
|
||||
@@ -470,17 +455,18 @@ class MonitorController {
|
||||
* @returns {Object} The response object with a success status, a message indicating the editing of the monitor, and the edited monitor data.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
editMonitor = async (req, res, next) => {
|
||||
try {
|
||||
editMonitor = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getMonitorByIdParamValidation.validateAsync(req.params);
|
||||
await editMonitorBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
const monitorId = req?.params?.monitorId;
|
||||
|
||||
try {
|
||||
const { monitorId } = req.params;
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("Team ID is required");
|
||||
}
|
||||
|
||||
await this.verifyTeamAccess(teamId, monitorId);
|
||||
|
||||
const editedMonitor = await this.db.editMonitor(monitorId, req.body);
|
||||
|
||||
@@ -490,10 +476,10 @@ class MonitorController {
|
||||
msg: this.stringService.monitorEdit,
|
||||
data: editedMonitor,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "editMonitor"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"editMonitor"
|
||||
);
|
||||
|
||||
/**
|
||||
* Pauses or resumes a monitor based on its current state.
|
||||
@@ -506,30 +492,29 @@ class MonitorController {
|
||||
* @returns {Object} The response object with a success status, a message indicating the new state of the monitor, and the updated monitor data.
|
||||
* @throws {Error} If there is an error during the process.
|
||||
*/
|
||||
pauseMonitor = async (req, res, next) => {
|
||||
try {
|
||||
pauseMonitor = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await pauseMonitorParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
}
|
||||
|
||||
try {
|
||||
const monitorId = req.params.monitorId;
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("Team ID is required");
|
||||
}
|
||||
|
||||
await this.verifyTeamAccess(teamId, monitorId);
|
||||
|
||||
const monitor = await this.db.pauseMonitor({ monitorId });
|
||||
monitor.isActive === true
|
||||
? await this.jobQueue.resumeJob(monitor._id, monitor)
|
||||
: await this.jobQueue.pauseJob(monitor);
|
||||
monitor.isActive === true ? await this.jobQueue.resumeJob(monitor._id, monitor) : await this.jobQueue.pauseJob(monitor);
|
||||
|
||||
return res.success({
|
||||
msg: monitor.isActive
|
||||
? this.stringService.monitorResume
|
||||
: this.stringService.monitorPause,
|
||||
msg: monitor.isActive ? this.stringService.monitorResume : this.stringService.monitorPause,
|
||||
data: monitor,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "pauseMonitor"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"pauseMonitor"
|
||||
);
|
||||
|
||||
/**
|
||||
* Adds demo monitors for a team.
|
||||
@@ -542,22 +527,20 @@ class MonitorController {
|
||||
* @returns {Object} The response object with a success status, a message indicating the addition of demo monitors, and the number of demo monitors added.
|
||||
* @throws {Error} If there is an error during the process.
|
||||
*/
|
||||
addDemoMonitors = async (req, res, next) => {
|
||||
try {
|
||||
addDemoMonitors = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const { _id, teamId } = req.user;
|
||||
const demoMonitors = await this.db.addDemoMonitors(_id, teamId);
|
||||
await Promise.all(
|
||||
demoMonitors.map((monitor) => this.jobQueue.addJob(monitor._id, monitor))
|
||||
);
|
||||
await Promise.all(demoMonitors.map((monitor) => this.jobQueue.addJob(monitor._id, monitor)));
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.monitorDemoAdded,
|
||||
data: demoMonitors.length,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "addDemoMonitors"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"addDemoMonitors"
|
||||
);
|
||||
|
||||
/**
|
||||
* Sends a test email to verify email delivery functionality.
|
||||
@@ -570,8 +553,8 @@ class MonitorController {
|
||||
* @returns {Object} The response object with a success status and the email delivery message ID.
|
||||
* @throws {Error} If there is an error while sending the test email.
|
||||
*/
|
||||
sendTestEmail = async (req, res, next) => {
|
||||
try {
|
||||
sendTestEmail = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const { to } = req.body;
|
||||
if (!to || typeof to !== "string") {
|
||||
throw new Error(this.stringService.errorForValidEmailAddress);
|
||||
@@ -584,29 +567,23 @@ class MonitorController {
|
||||
const messageId = await this.emailService.sendEmail(to, subject, html);
|
||||
|
||||
if (!messageId) {
|
||||
return res.error({
|
||||
msg: "Failed to send test email.",
|
||||
});
|
||||
throw createServerError("Failed to send test email.");
|
||||
}
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.sendTestEmail,
|
||||
data: { messageId },
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "sendTestEmail"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"sendTestEmail"
|
||||
);
|
||||
|
||||
getMonitorsByTeamId = async (req, res, next) => {
|
||||
try {
|
||||
getMonitorsByTeamId = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
|
||||
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
}
|
||||
|
||||
try {
|
||||
let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
|
||||
const teamId = req.user.teamId;
|
||||
|
||||
@@ -624,20 +601,16 @@ class MonitorController {
|
||||
msg: this.stringService.monitorGetByTeamId,
|
||||
data: monitors,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMonitorsByTeamId"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getMonitorsByTeamId"
|
||||
);
|
||||
|
||||
getMonitorsAndSummaryByTeamId = async (req, res, next) => {
|
||||
try {
|
||||
getMonitorsAndSummaryByTeamId = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
|
||||
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
return next(handleValidationError(error, SERVICE_NAME));
|
||||
}
|
||||
|
||||
try {
|
||||
const { explain } = req;
|
||||
const { type } = req.query;
|
||||
const { teamId } = req.user;
|
||||
@@ -651,20 +624,16 @@ class MonitorController {
|
||||
msg: "OK", // TODO
|
||||
data: result,
|
||||
});
|
||||
} catch (error) {
|
||||
return next(handleError(error, SERVICE_NAME, "getMonitorsAndSummaryByTeamId"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getMonitorsAndSummaryByTeamId"
|
||||
);
|
||||
|
||||
getMonitorsWithChecksByTeamId = async (req, res, next) => {
|
||||
try {
|
||||
getMonitorsWithChecksByTeamId = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
|
||||
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
return next(handleValidationError(error, SERVICE_NAME));
|
||||
}
|
||||
|
||||
try {
|
||||
const { explain } = req;
|
||||
let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
|
||||
const { teamId } = req.user;
|
||||
@@ -684,23 +653,23 @@ class MonitorController {
|
||||
msg: "OK",
|
||||
data: result,
|
||||
});
|
||||
} catch (error) {
|
||||
return next(handleError(error, SERVICE_NAME, "getMonitorsWithChecksByTeamId"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getMonitorsWithChecksByTeamId"
|
||||
);
|
||||
|
||||
seedDb = async (req, res, next) => {
|
||||
try {
|
||||
seedDb = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const { _id, teamId } = req.user;
|
||||
await seedDb(_id, teamId);
|
||||
res.success({ msg: "Database seeded" });
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "seedDb"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"seedDb"
|
||||
);
|
||||
|
||||
exportMonitorsToCSV = async (req, res, next) => {
|
||||
try {
|
||||
exportMonitorsToCSV = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const { teamId } = req.user;
|
||||
|
||||
const monitors = await this.db.getMonitorsByTeamId({ teamId });
|
||||
@@ -730,10 +699,10 @@ class MonitorController {
|
||||
"Content-Disposition": "attachment; filename=monitors.csv",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "exportMonitorsToCSV"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"exportMonitorsToCSV"
|
||||
);
|
||||
}
|
||||
|
||||
export default MonitorController;
|
||||
@@ -1,22 +1,8 @@
|
||||
import {
|
||||
triggerNotificationBodyValidation,
|
||||
createNotificationBodyValidation,
|
||||
} from "../validation/joi.js";
|
||||
import { handleError, handleValidationError } from "./controllerUtils.js";
|
||||
import { createNotificationBodyValidation } from "../validation/joi.js";
|
||||
import { asyncHandler } from "../utils/errorUtils.js";
|
||||
|
||||
const SERVICE_NAME = "NotificationController";
|
||||
|
||||
const NOTIFICATION_TYPES = {
|
||||
WEBHOOK: "webhook",
|
||||
TELEGRAM: "telegram",
|
||||
};
|
||||
|
||||
const PLATFORMS = {
|
||||
SLACK: "slack",
|
||||
DISCORD: "discord",
|
||||
TELEGRAM: "telegram",
|
||||
};
|
||||
|
||||
class NotificationController {
|
||||
constructor({ notificationService, stringService, statusService, db }) {
|
||||
this.notificationService = notificationService;
|
||||
@@ -25,8 +11,8 @@ class NotificationController {
|
||||
this.db = db;
|
||||
}
|
||||
|
||||
testNotification = async (req, res, next) => {
|
||||
try {
|
||||
testNotification = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const notification = req.body;
|
||||
|
||||
const success = await this.notificationService.sendTestNotification(notification);
|
||||
@@ -41,96 +27,150 @@ class NotificationController {
|
||||
return res.success({
|
||||
msg: "Notification sent successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "testWebhook"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"testNotification"
|
||||
);
|
||||
|
||||
createNotification = async (req, res, next) => {
|
||||
try {
|
||||
createNotification = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await createNotificationBodyValidation.validateAsync(req.body, {
|
||||
abortEarly: false,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const body = req.body;
|
||||
const { _id, teamId } = req.user;
|
||||
body.userId = _id;
|
||||
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
const userId = req?.user?._id;
|
||||
if (!userId) {
|
||||
throw new Error("No user ID in request");
|
||||
}
|
||||
body.userId = userId;
|
||||
body.teamId = teamId;
|
||||
|
||||
const notification = await this.db.createNotification(body);
|
||||
return res.success({
|
||||
msg: "Notification created successfully",
|
||||
data: notification,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "createNotification"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"createNotification"
|
||||
);
|
||||
|
||||
getNotificationsByTeamId = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
const notifications = await this.db.getNotificationsByTeamId(teamId);
|
||||
|
||||
getNotificationsByTeamId = async (req, res, next) => {
|
||||
try {
|
||||
const notifications = await this.db.getNotificationsByTeamId(req.user.teamId);
|
||||
return res.success({
|
||||
msg: "Notifications fetched successfully",
|
||||
data: notifications,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getNotificationsByTeamId"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getNotificationsByTeamId"
|
||||
);
|
||||
|
||||
deleteNotification = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
const notification = await this.db.getNotificationById(req.params.id);
|
||||
if (!notification.teamId.equals(teamId)) {
|
||||
const error = new Error("Unauthorized");
|
||||
error.status = 403;
|
||||
throw error;
|
||||
}
|
||||
|
||||
deleteNotification = async (req, res, next) => {
|
||||
try {
|
||||
await this.db.deleteNotificationById(req.params.id);
|
||||
return res.success({
|
||||
msg: "Notification deleted successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteNotification"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"deleteNotification"
|
||||
);
|
||||
|
||||
getNotificationById = async (req, res, next) => {
|
||||
try {
|
||||
getNotificationById = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const notification = await this.db.getNotificationById(req.params.id);
|
||||
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
if (!notification.teamId.equals(teamId)) {
|
||||
const error = new Error("Unauthorized");
|
||||
error.status = 403;
|
||||
throw error;
|
||||
}
|
||||
return res.success({
|
||||
msg: "Notification fetched successfully",
|
||||
data: notification,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getNotificationById"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getNotificationById"
|
||||
);
|
||||
|
||||
editNotification = async (req, res, next) => {
|
||||
try {
|
||||
editNotification = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await createNotificationBodyValidation.validateAsync(req.body, {
|
||||
abortEarly: false,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const notification = await this.db.editNotification(req.params.id, req.body);
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
const notification = await this.db.getNotificationById(req.params.id);
|
||||
|
||||
if (!notification.teamId.equals(teamId)) {
|
||||
const error = new Error("Unauthorized");
|
||||
error.status = 403;
|
||||
throw error;
|
||||
}
|
||||
|
||||
const editedNotification = await this.db.editNotification(req.params.id, req.body);
|
||||
return res.success({
|
||||
msg: "Notification updated successfully",
|
||||
data: notification,
|
||||
data: editedNotification,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "editNotification"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"editNotification"
|
||||
);
|
||||
|
||||
testAllNotifications = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const monitorId = req.body.monitorId;
|
||||
const teamId = req?.user?.teamId;
|
||||
if (!teamId) {
|
||||
throw new Error("No team ID in request");
|
||||
}
|
||||
|
||||
testAllNotifications = async (req, res, next) => {
|
||||
try {
|
||||
const { monitorId } = req.body;
|
||||
const monitor = await this.db.getMonitorById(monitorId);
|
||||
|
||||
if (!monitor.teamId.equals(teamId)) {
|
||||
const error = new Error("Unauthorized");
|
||||
error.status = 403;
|
||||
throw error;
|
||||
}
|
||||
|
||||
const notifications = monitor.notifications;
|
||||
if (notifications.length === 0) throw new Error("No notifications");
|
||||
const result = await this.notificationService.testAllNotifications(notifications);
|
||||
@@ -138,10 +178,10 @@ class NotificationController {
|
||||
return res.success({
|
||||
msg: "All notifications sent successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "testAllNotifications"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"testAllNotifications"
|
||||
);
|
||||
}
|
||||
|
||||
export default NotificationController;
|
||||
@@ -1,4 +1,4 @@
|
||||
import { handleError } from "./controllerUtils.js";
|
||||
import { asyncHandler } from "../utils/errorUtils.js";
|
||||
|
||||
const SERVICE_NAME = "JobQueueController";
|
||||
|
||||
@@ -8,82 +8,76 @@ class JobQueueController {
|
||||
this.stringService = stringService;
|
||||
}
|
||||
|
||||
getMetrics = async (req, res, next) => {
|
||||
try {
|
||||
getMetrics = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const metrics = await this.jobQueue.getMetrics();
|
||||
res.success({
|
||||
msg: this.stringService.queueGetMetrics,
|
||||
data: metrics,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMetrics"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getMetrics"
|
||||
);
|
||||
|
||||
getJobs = async (req, res, next) => {
|
||||
try {
|
||||
getJobs = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const jobs = await this.jobQueue.getJobs();
|
||||
return res.success({
|
||||
msg: this.stringService.queueGetJobs,
|
||||
data: jobs,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getJobs"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getJobs"
|
||||
);
|
||||
|
||||
getAllMetrics = async (req, res, next) => {
|
||||
try {
|
||||
getAllMetrics = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const jobs = await this.jobQueue.getJobs();
|
||||
const metrics = await this.jobQueue.getMetrics();
|
||||
return res.success({
|
||||
msg: this.stringService.queueGetAllMetrics,
|
||||
data: { jobs, metrics },
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getAllMetrics"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getAllMetrics"
|
||||
);
|
||||
|
||||
addJob = async (req, res, next) => {
|
||||
try {
|
||||
addJob = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await this.jobQueue.addJob(Math.random().toString(36).substring(7));
|
||||
return res.success({
|
||||
msg: this.stringService.queueAddJob,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "addJob"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"addJob"
|
||||
);
|
||||
|
||||
flushQueue = async (req, res, next) => {
|
||||
try {
|
||||
flushQueue = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const result = await this.jobQueue.flushQueues();
|
||||
return res.success({
|
||||
msg: this.stringService.jobQueueFlush,
|
||||
data: result,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "flushQueue"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"flushQueue"
|
||||
);
|
||||
|
||||
checkQueueHealth = async (req, res, next) => {
|
||||
try {
|
||||
checkQueueHealth = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const stuckQueues = await this.jobQueue.checkQueueHealth();
|
||||
return res.success({
|
||||
msg: this.stringService.queueHealthCheck,
|
||||
data: stuckQueues,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "checkQueueHealth"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"checkQueueHealth"
|
||||
);
|
||||
}
|
||||
export default JobQueueController;
|
||||
@@ -1,6 +1,7 @@
|
||||
import { updateAppSettingsBodyValidation } from "../validation/joi.js";
|
||||
import { handleValidationError, handleError } from "./controllerUtils.js";
|
||||
import { sendTestEmailBodyValidation } from "../validation/joi.js";
|
||||
import { asyncHandler, createServerError } from "../utils/errorUtils.js";
|
||||
|
||||
const SERVICE_NAME = "SettingsController";
|
||||
|
||||
class SettingsController {
|
||||
@@ -32,45 +33,44 @@ class SettingsController {
|
||||
return returnSettings;
|
||||
};
|
||||
|
||||
getAppSettings = async (req, res, next) => {
|
||||
const dbSettings = await this.settingsService.getDBSettings();
|
||||
getAppSettings = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const dbSettings = await this.settingsService.getDBSettings();
|
||||
|
||||
const returnSettings = this.buildAppSettings(dbSettings);
|
||||
return res.success({
|
||||
msg: this.stringService.getAppSettings,
|
||||
data: returnSettings,
|
||||
});
|
||||
};
|
||||
const returnSettings = this.buildAppSettings(dbSettings);
|
||||
return res.success({
|
||||
msg: this.stringService.getAppSettings,
|
||||
data: returnSettings,
|
||||
});
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getAppSettings"
|
||||
);
|
||||
|
||||
updateAppSettings = async (req, res, next) => {
|
||||
try {
|
||||
updateAppSettings = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await updateAppSettingsBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const updatedSettings = await this.db.updateAppSettings(req.body);
|
||||
const returnSettings = this.buildAppSettings(updatedSettings);
|
||||
return res.success({
|
||||
msg: this.stringService.updateAppSettings,
|
||||
data: returnSettings,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "updateAppSettings"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"updateAppSettings"
|
||||
);
|
||||
|
||||
sendTestEmail = async (req, res, next) => {
|
||||
try {
|
||||
await sendTestEmailBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
sendTestEmail = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
await sendTestEmailBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const {
|
||||
to,
|
||||
systemEmailHost,
|
||||
@@ -107,20 +107,17 @@ class SettingsController {
|
||||
});
|
||||
|
||||
if (!messageId) {
|
||||
return res.error({
|
||||
msg: "Failed to send test email.",
|
||||
});
|
||||
throw createServerError("Failed to send test email.");
|
||||
}
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.sendTestEmail,
|
||||
data: { messageId },
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"sendTestEmail"
|
||||
);
|
||||
}
|
||||
|
||||
export default SettingsController;
|
||||
@@ -1,10 +1,5 @@
|
||||
import { handleError, handleValidationError } from "./controllerUtils.js";
|
||||
import {
|
||||
createStatusPageBodyValidation,
|
||||
getStatusPageParamValidation,
|
||||
getStatusPageQueryValidation,
|
||||
imageValidation,
|
||||
} from "../validation/joi.js";
|
||||
import { createStatusPageBodyValidation, getStatusPageParamValidation, getStatusPageQueryValidation, imageValidation } from "../validation/joi.js";
|
||||
import { asyncHandler } from "../utils/errorUtils.js";
|
||||
|
||||
const SERVICE_NAME = "statusPageController";
|
||||
|
||||
@@ -14,16 +9,11 @@ class StatusPageController {
|
||||
this.stringService = stringService;
|
||||
}
|
||||
|
||||
createStatusPage = async (req, res, next) => {
|
||||
try {
|
||||
createStatusPage = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await createStatusPageBodyValidation.validateAsync(req.body);
|
||||
await imageValidation.validateAsync(req.file);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { _id, teamId } = req.user;
|
||||
const statusPage = await this.db.createStatusPage({
|
||||
statusPageData: req.body,
|
||||
@@ -35,21 +25,16 @@ class StatusPageController {
|
||||
msg: this.stringService.statusPageCreate,
|
||||
data: statusPage,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "createStatusPage"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"createStatusPage"
|
||||
);
|
||||
|
||||
updateStatusPage = async (req, res, next) => {
|
||||
try {
|
||||
updateStatusPage = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await createStatusPageBodyValidation.validateAsync(req.body);
|
||||
await imageValidation.validateAsync(req.file);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const statusPage = await this.db.updateStatusPage(req.body, req.file);
|
||||
if (statusPage === null) {
|
||||
const error = new Error(this.stringService.statusPageNotFound);
|
||||
@@ -60,45 +45,40 @@ class StatusPageController {
|
||||
msg: this.stringService.statusPageUpdate,
|
||||
data: statusPage,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "updateStatusPage"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"updateStatusPage"
|
||||
);
|
||||
|
||||
getStatusPage = async (req, res, next) => {
|
||||
try {
|
||||
getStatusPage = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const statusPage = await this.db.getStatusPage();
|
||||
return res.success({
|
||||
msg: this.stringService.statusPageByUrl,
|
||||
data: statusPage,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getStatusPage"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getStatusPage"
|
||||
);
|
||||
|
||||
getStatusPageByUrl = async (req, res, next) => {
|
||||
try {
|
||||
getStatusPageByUrl = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await getStatusPageParamValidation.validateAsync(req.params);
|
||||
await getStatusPageQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const statusPage = await this.db.getStatusPageByUrl(req.params.url, req.query.type);
|
||||
return res.success({
|
||||
msg: this.stringService.statusPageByUrl,
|
||||
data: statusPage,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getStatusPageByUrl"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getStatusPageByUrl"
|
||||
);
|
||||
|
||||
getStatusPagesByTeamId = async (req, res, next) => {
|
||||
try {
|
||||
getStatusPagesByTeamId = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
const teamId = req.user.teamId;
|
||||
const statusPages = await this.db.getStatusPagesByTeamId(teamId);
|
||||
|
||||
@@ -106,21 +86,21 @@ class StatusPageController {
|
||||
msg: this.stringService.statusPageByTeamId,
|
||||
data: statusPages,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getStatusPageByTeamId"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"getStatusPagesByTeamId"
|
||||
);
|
||||
|
||||
deleteStatusPage = async (req, res, next) => {
|
||||
try {
|
||||
deleteStatusPage = asyncHandler(
|
||||
async (req, res, next) => {
|
||||
await this.db.deleteStatusPage(req.params.url);
|
||||
return res.success({
|
||||
msg: this.stringService.statusPageDelete,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteStatusPage"));
|
||||
}
|
||||
};
|
||||
},
|
||||
SERVICE_NAME,
|
||||
"deleteStatusPage"
|
||||
);
|
||||
}
|
||||
|
||||
export default StatusPageController;
|
||||
@@ -156,10 +156,7 @@ MonitorSchema.pre("deleteMany", async function (next) {
|
||||
} else {
|
||||
await Check.deleteMany({ monitorId: monitor._id });
|
||||
}
|
||||
await StatusPage.updateMany(
|
||||
{ monitors: monitor._id },
|
||||
{ $pull: { monitors: monitor._id } }
|
||||
);
|
||||
await StatusPage.updateMany({ monitors: monitor._id }, { $pull: { monitors: monitor._id } });
|
||||
await MonitorStats.deleteMany({ monitorId: monitor._id.toString() });
|
||||
}
|
||||
next();
|
||||
|
||||
@@ -89,8 +89,7 @@ class MongoDB {
|
||||
|
||||
connect = async () => {
|
||||
try {
|
||||
const connectionString =
|
||||
this.appSettings.dbConnectionString || "mongodb://localhost:27017/uptime_db";
|
||||
const connectionString = this.appSettings.dbConnectionString || "mongodb://localhost:27017/uptime_db";
|
||||
await mongoose.connect(connectionString);
|
||||
// If there are no AppSettings, create one
|
||||
await AppSettings.findOneAndUpdate(
|
||||
|
||||
@@ -58,26 +58,13 @@ const createChecks = async (checks) => {
|
||||
* @returns {Promise<Array<Check>>}
|
||||
* @throws {Error}
|
||||
*/
|
||||
const getChecksByMonitor = async ({
|
||||
monitorId,
|
||||
type,
|
||||
sortOrder,
|
||||
dateRange,
|
||||
filter,
|
||||
ack,
|
||||
page,
|
||||
rowsPerPage,
|
||||
status,
|
||||
}) => {
|
||||
const getChecksByMonitor = async ({ monitorId, type, sortOrder, dateRange, filter, ack, page, rowsPerPage, status }) => {
|
||||
try {
|
||||
status = status === "true" ? true : status === "false" ? false : undefined;
|
||||
page = parseInt(page);
|
||||
rowsPerPage = parseInt(rowsPerPage);
|
||||
|
||||
const ackStage =
|
||||
ack === "true"
|
||||
? { ack: true }
|
||||
: { $or: [{ ack: false }, { ack: { $exists: false } }] };
|
||||
const ackStage = ack === "true" ? { ack: true } : { $or: [{ ack: false }, { ack: { $exists: false } }] };
|
||||
|
||||
// Match
|
||||
const matchStage = {
|
||||
@@ -158,23 +145,12 @@ const getChecksByMonitor = async ({
|
||||
}
|
||||
};
|
||||
|
||||
const getChecksByTeam = async ({
|
||||
sortOrder,
|
||||
dateRange,
|
||||
filter,
|
||||
ack,
|
||||
page,
|
||||
rowsPerPage,
|
||||
teamId,
|
||||
}) => {
|
||||
const getChecksByTeam = async ({ sortOrder, dateRange, filter, ack, page, rowsPerPage, teamId }) => {
|
||||
try {
|
||||
page = parseInt(page);
|
||||
rowsPerPage = parseInt(rowsPerPage);
|
||||
|
||||
const ackStage =
|
||||
ack === "true"
|
||||
? { ack: true }
|
||||
: { $or: [{ ack: false }, { ack: { $exists: false } }] };
|
||||
const ackStage = ack === "true" ? { ack: true } : { $or: [{ ack: false }, { ack: { $exists: false } }] };
|
||||
|
||||
const matchStage = {
|
||||
teamId: new ObjectId(teamId),
|
||||
@@ -264,11 +240,7 @@ const getChecksByTeam = async ({
|
||||
*/
|
||||
const ackCheck = async (checkId, teamId, ack) => {
|
||||
try {
|
||||
const updatedCheck = await Check.findOneAndUpdate(
|
||||
{ _id: checkId, teamId: teamId },
|
||||
{ $set: { ack, ackAt: new Date() } },
|
||||
{ new: true }
|
||||
);
|
||||
const updatedCheck = await Check.findOneAndUpdate({ _id: checkId, teamId: teamId }, { $set: { ack, ackAt: new Date() } }, { new: true });
|
||||
|
||||
if (!updatedCheck) {
|
||||
throw new Error("Check not found");
|
||||
@@ -293,10 +265,7 @@ const ackCheck = async (checkId, teamId, ack) => {
|
||||
*/
|
||||
const ackAllChecks = async (monitorId, teamId, ack, path) => {
|
||||
try {
|
||||
const updatedChecks = await Check.updateMany(
|
||||
path === "monitor" ? { monitorId } : { teamId },
|
||||
{ $set: { ack, ackAt: new Date() } }
|
||||
);
|
||||
const updatedChecks = await Check.updateMany(path === "monitor" ? { monitorId } : { teamId }, { $set: { ack, ackAt: new Date() } });
|
||||
return updatedChecks.modifiedCount;
|
||||
} catch (error) {
|
||||
error.service = SERVICE_NAME;
|
||||
@@ -317,9 +286,7 @@ const getChecksSummaryByTeamId = async ({ teamId }) => {
|
||||
const matchStage = {
|
||||
teamId: new ObjectId(teamId),
|
||||
};
|
||||
const checks = await Check.aggregate(
|
||||
buildChecksSummaryByTeamIdPipeline({ matchStage })
|
||||
);
|
||||
const checks = await Check.aggregate(buildChecksSummaryByTeamIdPipeline({ matchStage }));
|
||||
return checks[0].summary;
|
||||
} catch (error) {
|
||||
error.service = SERVICE_NAME;
|
||||
|
||||
@@ -10,20 +10,12 @@ const buildChecksSummaryByTeamIdPipeline = ({ matchStage }) => {
|
||||
totalChecks: { $sum: { $cond: [{ $eq: ["$status", false] }, 1, 0] } },
|
||||
resolvedChecks: {
|
||||
$sum: {
|
||||
$cond: [
|
||||
{ $and: [{ $eq: ["$ack", true] }, { $eq: ["$status", false] }] },
|
||||
1,
|
||||
0,
|
||||
],
|
||||
$cond: [{ $and: [{ $eq: ["$ack", true] }, { $eq: ["$status", false] }] }, 1, 0],
|
||||
},
|
||||
},
|
||||
downChecks: {
|
||||
$sum: {
|
||||
$cond: [
|
||||
{ $and: [{ $eq: ["$ack", false] }, { $eq: ["$status", false] }] },
|
||||
1,
|
||||
0,
|
||||
],
|
||||
$cond: [{ $and: [{ $eq: ["$ack", false] }, { $eq: ["$status", false] }] }, 1, 0],
|
||||
},
|
||||
},
|
||||
cannotResolveChecks: {
|
||||
|
||||
@@ -2,11 +2,7 @@ import Monitor from "../../models/Monitor.js";
|
||||
import { ObjectId } from "mongodb";
|
||||
|
||||
const SERVICE_NAME = "diagnosticModule";
|
||||
import {
|
||||
buildMonitorSummaryByTeamIdPipeline,
|
||||
buildMonitorsByTeamIdPipeline,
|
||||
buildFilteredMonitorsByTeamIdPipeline,
|
||||
} from "./monitorModuleQueries.js";
|
||||
import { buildMonitorSummaryByTeamIdPipeline, buildMonitorsByTeamIdPipeline, buildFilteredMonitorsByTeamIdPipeline } from "./monitorModuleQueries.js";
|
||||
|
||||
const getMonitorsByTeamIdExecutionStats = async (req) => {
|
||||
try {
|
||||
@@ -24,13 +20,9 @@ const getMonitorsByTeamIdExecutionStats = async (req) => {
|
||||
matchStage.type = Array.isArray(type) ? { $in: type } : type;
|
||||
}
|
||||
|
||||
const summary = await Monitor.aggregate(
|
||||
buildMonitorSummaryByTeamIdPipeline({ matchStage })
|
||||
).explain("executionStats");
|
||||
const summary = await Monitor.aggregate(buildMonitorSummaryByTeamIdPipeline({ matchStage })).explain("executionStats");
|
||||
|
||||
const monitors = await Monitor.aggregate(
|
||||
buildMonitorsByTeamIdPipeline({ matchStage, field, order })
|
||||
).explain("executionStats");
|
||||
const monitors = await Monitor.aggregate(buildMonitorsByTeamIdPipeline({ matchStage, field, order })).explain("executionStats");
|
||||
|
||||
const filteredMonitors = await Monitor.aggregate(
|
||||
buildFilteredMonitorsByTeamIdPipeline({
|
||||
|
||||
@@ -23,14 +23,10 @@ const createHardwareCheck = async (hardwareCheckData) => {
|
||||
if (monitor.uptimePercentage === undefined) {
|
||||
newUptimePercentage = status === true ? 1 : 0;
|
||||
} else {
|
||||
newUptimePercentage =
|
||||
(monitor.uptimePercentage * (n - 1) + (status === true ? 1 : 0)) / n;
|
||||
newUptimePercentage = (monitor.uptimePercentage * (n - 1) + (status === true ? 1 : 0)) / n;
|
||||
}
|
||||
|
||||
await Monitor.findOneAndUpdate(
|
||||
{ _id: monitorId },
|
||||
{ uptimePercentage: newUptimePercentage }
|
||||
);
|
||||
await Monitor.findOneAndUpdate({ _id: monitorId }, { uptimePercentage: newUptimePercentage });
|
||||
|
||||
const hardwareCheck = await new HardwareCheck({
|
||||
...hardwareCheckData,
|
||||
|
||||
@@ -34,10 +34,11 @@ const createMaintenanceWindow = async (maintenanceWindowData) => {
|
||||
}
|
||||
};
|
||||
|
||||
const getMaintenanceWindowById = async (maintenanceWindowId) => {
|
||||
const getMaintenanceWindowById = async ({ id, teamId }) => {
|
||||
try {
|
||||
const maintenanceWindow = await MaintenanceWindow.findById({
|
||||
_id: maintenanceWindowId,
|
||||
const maintenanceWindow = await MaintenanceWindow.findOne({
|
||||
_id: id,
|
||||
teamId: teamId,
|
||||
});
|
||||
return maintenanceWindow;
|
||||
} catch (error) {
|
||||
@@ -63,8 +64,7 @@ const getMaintenanceWindowsByTeamId = async (teamId, query) => {
|
||||
|
||||
if (active !== undefined) maintenanceQuery.active = active;
|
||||
|
||||
const maintenanceWindowCount =
|
||||
await MaintenanceWindow.countDocuments(maintenanceQuery);
|
||||
const maintenanceWindowCount = await MaintenanceWindow.countDocuments(maintenanceQuery);
|
||||
|
||||
// Pagination
|
||||
let skip = 0;
|
||||
@@ -78,10 +78,7 @@ const getMaintenanceWindowsByTeamId = async (teamId, query) => {
|
||||
sort[field] = order === "asc" ? 1 : -1;
|
||||
}
|
||||
|
||||
const maintenanceWindows = await MaintenanceWindow.find(maintenanceQuery)
|
||||
.skip(skip)
|
||||
.limit(rowsPerPage)
|
||||
.sort(sort);
|
||||
const maintenanceWindows = await MaintenanceWindow.find(maintenanceQuery).skip(skip).limit(rowsPerPage).sort(sort);
|
||||
|
||||
return { maintenanceWindows, maintenanceWindowCount };
|
||||
} catch (error) {
|
||||
@@ -99,10 +96,11 @@ const getMaintenanceWindowsByTeamId = async (teamId, query) => {
|
||||
* @returns {Promise<Array<MaintenanceWindow>>} An array of MaintenanceWindow documents.
|
||||
* @throws {Error} If there is an error retrieving the documents.
|
||||
*/
|
||||
const getMaintenanceWindowsByMonitorId = async (monitorId) => {
|
||||
const getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }) => {
|
||||
try {
|
||||
const maintenanceWindows = await MaintenanceWindow.find({
|
||||
monitorId: monitorId,
|
||||
teamId: teamId,
|
||||
});
|
||||
return maintenanceWindows;
|
||||
} catch (error) {
|
||||
@@ -120,10 +118,9 @@ const getMaintenanceWindowsByMonitorId = async (monitorId) => {
|
||||
* @returns {Promise<MaintenanceWindow>} The deleted MaintenanceWindow document.
|
||||
* @throws {Error} If there is an error deleting the document.
|
||||
*/
|
||||
const deleteMaintenanceWindowById = async (maintenanceWindowId) => {
|
||||
const deleteMaintenanceWindowById = async ({ id, teamId }) => {
|
||||
try {
|
||||
const maintenanceWindow =
|
||||
await MaintenanceWindow.findByIdAndDelete(maintenanceWindowId);
|
||||
const maintenanceWindow = await MaintenanceWindow.findOneAndDelete({ _id: id, teamId });
|
||||
return maintenanceWindow;
|
||||
} catch (error) {
|
||||
error.service = SERVICE_NAME;
|
||||
@@ -172,13 +169,9 @@ const deleteMaintenanceWindowByUserId = async (userId) => {
|
||||
}
|
||||
};
|
||||
|
||||
const editMaintenanceWindowById = async (maintenanceWindowId, maintenanceWindowData) => {
|
||||
const editMaintenanceWindowById = async ({ id, body, teamId }) => {
|
||||
try {
|
||||
const editedMaintenanceWindow = await MaintenanceWindow.findByIdAndUpdate(
|
||||
maintenanceWindowId,
|
||||
maintenanceWindowData,
|
||||
{ new: true }
|
||||
);
|
||||
const editedMaintenanceWindow = await MaintenanceWindow.findByIdAndUpdate(id, body, { new: true });
|
||||
return editedMaintenanceWindow;
|
||||
} catch (error) {
|
||||
error.service = SERVICE_NAME;
|
||||
|
||||
@@ -56,53 +56,6 @@ const getAllMonitors = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get all monitors with uptime stats for 1,7,30, and 90 days
|
||||
* @async
|
||||
* @param {Express.Request} req
|
||||
* @param {Express.Response} res
|
||||
* @returns {Promise<Array<Monitor>>}
|
||||
* @throws {Error}
|
||||
*/
|
||||
const getAllMonitorsWithUptimeStats = async () => {
|
||||
const timeRanges = {
|
||||
1: new Date(Date.now() - 24 * 60 * 60 * 1000),
|
||||
7: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
|
||||
30: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
|
||||
90: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000),
|
||||
};
|
||||
|
||||
try {
|
||||
const monitors = await Monitor.find();
|
||||
const monitorsWithStats = await Promise.all(
|
||||
monitors.map(async (monitor) => {
|
||||
const model = CHECK_MODEL_LOOKUP[monitor.type];
|
||||
|
||||
const uptimeStats = await Promise.all(
|
||||
Object.entries(timeRanges).map(async ([days, startDate]) => {
|
||||
const checks = await model.find({
|
||||
monitorId: monitor._id,
|
||||
createdAt: { $gte: startDate },
|
||||
});
|
||||
return [days, getUptimePercentage(checks)];
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
...monitor.toObject(),
|
||||
...Object.fromEntries(uptimeStats),
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return monitorsWithStats;
|
||||
} catch (error) {
|
||||
error.service = SERVICE_NAME;
|
||||
error.method = "getAllMonitorsWithUptimeStats";
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Function to calculate uptime duration based on the most recent check.
|
||||
* @param {Array} checks Array of check objects.
|
||||
@@ -285,10 +238,7 @@ const groupChecksByTime = (checks, dateRange) => {
|
||||
return acc;
|
||||
}
|
||||
|
||||
const time =
|
||||
dateRange === "day"
|
||||
? checkDate.setMinutes(0, 0, 0)
|
||||
: checkDate.toISOString().split("T")[0];
|
||||
const time = dateRange === "day" ? checkDate.setMinutes(0, 0, 0) : checkDate.toISOString().split("T")[0];
|
||||
|
||||
if (!acc[time]) {
|
||||
acc[time] = { time, checks: [] };
|
||||
@@ -306,9 +256,7 @@ const groupChecksByTime = (checks, dateRange) => {
|
||||
const calculateGroupStats = (group) => {
|
||||
const totalChecks = group.checks.length;
|
||||
|
||||
const checksWithResponseTime = group.checks.filter(
|
||||
(check) => typeof check.responseTime === "number" && !Number.isNaN(check.responseTime)
|
||||
);
|
||||
const checksWithResponseTime = group.checks.filter((check) => typeof check.responseTime === "number" && !Number.isNaN(check.responseTime));
|
||||
|
||||
return {
|
||||
time: group.time,
|
||||
@@ -317,8 +265,7 @@ const calculateGroupStats = (group) => {
|
||||
totalIncidents: group.checks.filter((check) => !check.status).length,
|
||||
avgResponseTime:
|
||||
checksWithResponseTime.length > 0
|
||||
? checksWithResponseTime.reduce((sum, check) => sum + check.responseTime, 0) /
|
||||
checksWithResponseTime.length
|
||||
? checksWithResponseTime.reduce((sum, check) => sum + check.responseTime, 0) / checksWithResponseTime.length
|
||||
: 0,
|
||||
};
|
||||
};
|
||||
@@ -344,29 +291,15 @@ const getUptimeDetailsById = async ({ monitorId, dateRange, normalize }) => {
|
||||
|
||||
const dateString = formatLookup[dateRange];
|
||||
|
||||
const results = await Check.aggregate(
|
||||
buildUptimeDetailsPipeline(monitorId, dates, dateString)
|
||||
);
|
||||
const results = await Check.aggregate(buildUptimeDetailsPipeline(monitorId, dates, dateString));
|
||||
|
||||
const monitorData = results[0];
|
||||
|
||||
monitorData.groupedUpChecks = NormalizeDataUptimeDetails(
|
||||
monitorData.groupedUpChecks,
|
||||
10,
|
||||
100
|
||||
);
|
||||
monitorData.groupedUpChecks = NormalizeDataUptimeDetails(monitorData.groupedUpChecks, 10, 100);
|
||||
|
||||
monitorData.groupedDownChecks = NormalizeDataUptimeDetails(
|
||||
monitorData.groupedDownChecks,
|
||||
10,
|
||||
100
|
||||
);
|
||||
monitorData.groupedDownChecks = NormalizeDataUptimeDetails(monitorData.groupedDownChecks, 10, 100);
|
||||
|
||||
const normalizedGroupChecks = NormalizeDataUptimeDetails(
|
||||
monitorData.groupedChecks,
|
||||
10,
|
||||
100
|
||||
);
|
||||
const normalizedGroupChecks = NormalizeDataUptimeDetails(monitorData.groupedChecks, 10, 100);
|
||||
|
||||
monitorData.groupedChecks = normalizedGroupChecks;
|
||||
const monitorStats = await MonitorStats.findOne({ monitorId });
|
||||
@@ -386,14 +319,7 @@ const getUptimeDetailsById = async ({ monitorId, dateRange, normalize }) => {
|
||||
* @returns {Promise<Monitor>}
|
||||
* @throws {Error}
|
||||
*/
|
||||
const getMonitorStatsById = async ({
|
||||
monitorId,
|
||||
limit,
|
||||
sortOrder,
|
||||
dateRange,
|
||||
numToDisplay,
|
||||
normalize,
|
||||
}) => {
|
||||
const getMonitorStatsById = async ({ monitorId, limit, sortOrder, dateRange, numToDisplay, normalize }) => {
|
||||
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
|
||||
try {
|
||||
// Get monitor, if we can't find it, abort with error
|
||||
@@ -408,12 +334,7 @@ const getMonitorStatsById = async ({
|
||||
// Get Checks for monitor in date range requested
|
||||
const model = CHECK_MODEL_LOOKUP[monitor.type];
|
||||
const dates = getDateRange(dateRange);
|
||||
const { checksAll, checksForDateRange } = await getMonitorChecks(
|
||||
monitorId,
|
||||
model,
|
||||
dates,
|
||||
sort
|
||||
);
|
||||
const { checksAll, checksForDateRange } = await getMonitorChecks(monitorId, model, dates, sort);
|
||||
|
||||
// Build monitor stats
|
||||
const monitorStats = {
|
||||
@@ -423,20 +344,10 @@ const getMonitorStatsById = async ({
|
||||
latestResponseTime: getLatestResponseTime(checksAll),
|
||||
periodIncidents: getIncidents(checksForDateRange),
|
||||
periodTotalChecks: checksForDateRange.length,
|
||||
checks: processChecksForDisplay(
|
||||
NormalizeData,
|
||||
checksForDateRange,
|
||||
numToDisplay,
|
||||
normalize
|
||||
),
|
||||
checks: processChecksForDisplay(NormalizeData, checksForDateRange, numToDisplay, normalize),
|
||||
};
|
||||
|
||||
if (
|
||||
monitor.type === "http" ||
|
||||
monitor.type === "ping" ||
|
||||
monitor.type === "docker" ||
|
||||
monitor.type === "port"
|
||||
) {
|
||||
if (monitor.type === "http" || monitor.type === "ping" || monitor.type === "docker" || monitor.type === "port") {
|
||||
// HTTP/PING Specific stats
|
||||
monitorStats.periodAvgResponseTime = getAverageResponseTime(checksForDateRange);
|
||||
monitorStats.periodUptime = getUptimePercentage(checksForDateRange);
|
||||
@@ -463,9 +374,7 @@ const getHardwareDetailsById = async ({ monitorId, dateRange }) => {
|
||||
month: "%Y-%m-%dT00:00:00Z",
|
||||
};
|
||||
const dateString = formatLookup[dateRange];
|
||||
const hardwareStats = await HardwareCheck.aggregate(
|
||||
buildHardwareDetailsPipeline(monitor, dates, dateString)
|
||||
);
|
||||
const hardwareStats = await HardwareCheck.aggregate(buildHardwareDetailsPipeline(monitor, dates, dateString));
|
||||
|
||||
const monitorStats = {
|
||||
...monitor.toObject(),
|
||||
@@ -505,16 +414,18 @@ const getMonitorById = async (monitorId) => {
|
||||
}
|
||||
};
|
||||
|
||||
const getMonitorsByTeamId = async ({
|
||||
limit,
|
||||
type,
|
||||
page,
|
||||
rowsPerPage,
|
||||
filter,
|
||||
field,
|
||||
order,
|
||||
teamId,
|
||||
}) => {
|
||||
const getMonitorsByIds = async (monitorIds) => {
|
||||
try {
|
||||
const objectIds = monitorIds.map((id) => new ObjectId(id));
|
||||
return await Monitor.find({ _id: { $in: objectIds } }, { _id: 1, teamId: 1 }).lean();
|
||||
} catch (error) {
|
||||
error.service = SERVICE_NAME;
|
||||
error.method = "getMonitorsByIds";
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const getMonitorsByTeamId = async ({ limit, type, page, rowsPerPage, filter, field, order, teamId }) => {
|
||||
limit = parseInt(limit);
|
||||
page = parseInt(page);
|
||||
rowsPerPage = parseInt(rowsPerPage);
|
||||
@@ -528,14 +439,10 @@ const getMonitorsByTeamId = async ({
|
||||
matchStage.type = Array.isArray(type) ? { $in: type } : type;
|
||||
}
|
||||
|
||||
const summaryResult = await Monitor.aggregate(
|
||||
buildMonitorSummaryByTeamIdPipeline({ matchStage })
|
||||
);
|
||||
const summaryResult = await Monitor.aggregate(buildMonitorSummaryByTeamIdPipeline({ matchStage }));
|
||||
const summary = summaryResult[0];
|
||||
|
||||
const monitors = await Monitor.aggregate(
|
||||
buildMonitorsByTeamIdPipeline({ matchStage, field, order })
|
||||
);
|
||||
const monitors = await Monitor.aggregate(buildMonitorsByTeamIdPipeline({ matchStage, field, order }));
|
||||
|
||||
const filteredMonitors = await Monitor.aggregate(
|
||||
buildFilteredMonitorsByTeamIdPipeline({
|
||||
@@ -569,14 +476,10 @@ const getMonitorsAndSummaryByTeamId = async ({ type, explain, teamId }) => {
|
||||
}
|
||||
|
||||
if (explain === true) {
|
||||
return Monitor.aggregate(
|
||||
buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })
|
||||
).explain("executionStats");
|
||||
return Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })).explain("executionStats");
|
||||
}
|
||||
|
||||
const queryResult = await Monitor.aggregate(
|
||||
buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })
|
||||
);
|
||||
const queryResult = await Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage }));
|
||||
const { monitors, summary } = queryResult?.[0] ?? {};
|
||||
return { monitors, summary };
|
||||
} catch (error) {
|
||||
@@ -586,17 +489,7 @@ const getMonitorsAndSummaryByTeamId = async ({ type, explain, teamId }) => {
|
||||
}
|
||||
};
|
||||
|
||||
const getMonitorsWithChecksByTeamId = async ({
|
||||
limit,
|
||||
type,
|
||||
page,
|
||||
rowsPerPage,
|
||||
filter,
|
||||
field,
|
||||
order,
|
||||
teamId,
|
||||
explain,
|
||||
}) => {
|
||||
const getMonitorsWithChecksByTeamId = async ({ limit, type, page, rowsPerPage, filter, field, order, teamId, explain }) => {
|
||||
try {
|
||||
limit = parseInt(limit);
|
||||
page = parseInt(page);
|
||||
@@ -684,9 +577,7 @@ const createMonitor = async ({ body, teamId, userId }) => {
|
||||
*/
|
||||
const createBulkMonitors = async (req) => {
|
||||
try {
|
||||
const monitors = req.map(
|
||||
(item) => new Monitor({ ...item, notifications: undefined })
|
||||
);
|
||||
const monitors = req.map((item) => new Monitor({ ...item, notifications: undefined }));
|
||||
await Monitor.bulkSave(monitors);
|
||||
return monitors;
|
||||
} catch (error) {
|
||||
@@ -823,9 +714,9 @@ const pauseMonitor = async ({ monitorId }) => {
|
||||
|
||||
export {
|
||||
getAllMonitors,
|
||||
getAllMonitorsWithUptimeStats,
|
||||
getMonitorStatsById,
|
||||
getMonitorById,
|
||||
getMonitorsByIds,
|
||||
getMonitorsByTeamId,
|
||||
getMonitorsAndSummaryByTeamId,
|
||||
getMonitorsWithChecksByTeamId,
|
||||
|
||||
@@ -31,11 +31,7 @@ const buildUptimeDetailsPipeline = (monitorId, dates, dateString) => {
|
||||
$project: {
|
||||
_id: 0,
|
||||
percentage: {
|
||||
$cond: [
|
||||
{ $eq: ["$totalChecks", 0] },
|
||||
0,
|
||||
{ $divide: ["$upChecks", "$totalChecks"] },
|
||||
],
|
||||
$cond: [{ $eq: ["$totalChecks", 0] }, 0, { $divide: ["$upChecks", "$totalChecks"] }],
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -235,11 +231,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
|
||||
{
|
||||
$match: {
|
||||
$expr: {
|
||||
$and: [
|
||||
{ $eq: ["$monitorId", monitor._id] },
|
||||
{ $gte: ["$createdAt", dates.start] },
|
||||
{ $lte: ["$createdAt", dates.end] },
|
||||
],
|
||||
$and: [{ $eq: ["$monitorId", monitor._id] }, { $gte: ["$createdAt", dates.start] }, { $lte: ["$createdAt", dates.end] }],
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -326,10 +318,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
|
||||
input: "$disks",
|
||||
as: "diskArray",
|
||||
in: {
|
||||
$arrayElemAt: [
|
||||
"$$diskArray.read_speed_bytes",
|
||||
"$$diskIndex",
|
||||
],
|
||||
$arrayElemAt: ["$$diskArray.read_speed_bytes", "$$diskIndex"],
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -340,10 +329,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
|
||||
input: "$disks",
|
||||
as: "diskArray",
|
||||
in: {
|
||||
$arrayElemAt: [
|
||||
"$$diskArray.write_speed_bytes",
|
||||
"$$diskIndex",
|
||||
],
|
||||
$arrayElemAt: ["$$diskArray.write_speed_bytes", "$$diskIndex"],
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -354,10 +340,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
|
||||
input: "$disks",
|
||||
as: "diskArray",
|
||||
in: {
|
||||
$arrayElemAt: [
|
||||
"$$diskArray.total_bytes",
|
||||
"$$diskIndex",
|
||||
],
|
||||
$arrayElemAt: ["$$diskArray.total_bytes", "$$diskIndex"],
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -379,10 +362,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
|
||||
input: "$disks",
|
||||
as: "diskArray",
|
||||
in: {
|
||||
$arrayElemAt: [
|
||||
"$$diskArray.usage_percent",
|
||||
"$$diskIndex",
|
||||
],
|
||||
$arrayElemAt: ["$$diskArray.usage_percent", "$$diskIndex"],
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -556,26 +536,14 @@ const buildMonitorsAndSummaryByTeamIdPipeline = ({ matchStage }) => {
|
||||
];
|
||||
};
|
||||
|
||||
const buildMonitorsWithChecksByTeamIdPipeline = ({
|
||||
matchStage,
|
||||
filter,
|
||||
page,
|
||||
rowsPerPage,
|
||||
field,
|
||||
order,
|
||||
limit,
|
||||
type,
|
||||
}) => {
|
||||
const buildMonitorsWithChecksByTeamIdPipeline = ({ matchStage, filter, page, rowsPerPage, field, order, limit, type }) => {
|
||||
const skip = page && rowsPerPage ? page * rowsPerPage : 0;
|
||||
const sort = { [field]: order === "asc" ? 1 : -1 };
|
||||
const limitStage = rowsPerPage ? [{ $limit: rowsPerPage }] : [];
|
||||
|
||||
// Match name
|
||||
if (typeof filter !== "undefined" && field === "name") {
|
||||
matchStage.$or = [
|
||||
{ name: { $regex: filter, $options: "i" } },
|
||||
{ url: { $regex: filter, $options: "i" } },
|
||||
];
|
||||
matchStage.$or = [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }];
|
||||
}
|
||||
|
||||
// Match isActive
|
||||
@@ -667,37 +635,20 @@ const buildMonitorsWithChecksByTeamIdPipeline = ({
|
||||
return pipeline;
|
||||
};
|
||||
|
||||
const buildFilteredMonitorsByTeamIdPipeline = ({
|
||||
matchStage,
|
||||
filter,
|
||||
page,
|
||||
rowsPerPage,
|
||||
field,
|
||||
order,
|
||||
limit,
|
||||
type,
|
||||
}) => {
|
||||
const buildFilteredMonitorsByTeamIdPipeline = ({ matchStage, filter, page, rowsPerPage, field, order, limit, type }) => {
|
||||
const skip = page && rowsPerPage ? page * rowsPerPage : 0;
|
||||
const sort = { [field]: order === "asc" ? 1 : -1 };
|
||||
const limitStage = rowsPerPage ? [{ $limit: rowsPerPage }] : [];
|
||||
|
||||
if (typeof filter !== "undefined" && field === "name") {
|
||||
matchStage.$or = [
|
||||
{ name: { $regex: filter, $options: "i" } },
|
||||
{ url: { $regex: filter, $options: "i" } },
|
||||
];
|
||||
matchStage.$or = [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }];
|
||||
}
|
||||
|
||||
if (typeof filter !== "undefined" && field === "status") {
|
||||
matchStage.status = filter === "true";
|
||||
}
|
||||
|
||||
const pipeline = [
|
||||
{ $match: matchStage },
|
||||
{ $sort: sort },
|
||||
{ $skip: skip },
|
||||
...limitStage,
|
||||
];
|
||||
const pipeline = [{ $match: matchStage }, { $sort: sort }, { $skip: skip }, ...limitStage];
|
||||
|
||||
// Add checks
|
||||
if (limit) {
|
||||
@@ -792,10 +743,7 @@ const buildGetMonitorsByTeamIdPipeline = (req) => {
|
||||
? [
|
||||
{
|
||||
$match: {
|
||||
$or: [
|
||||
{ name: { $regex: filter, $options: "i" } },
|
||||
{ url: { $regex: filter, $options: "i" } },
|
||||
],
|
||||
$or: [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
@@ -32,9 +32,7 @@ const createNetworkCheck = async (networkCheckData) => {
|
||||
*/
|
||||
const getNetworkChecksByMonitorId = async (monitorId, limit = 100) => {
|
||||
try {
|
||||
const networkChecks = await NetworkCheck.find({ monitorId })
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(limit);
|
||||
const networkChecks = await NetworkCheck.find({ monitorId }).sort({ createdAt: -1 }).limit(limit);
|
||||
return networkChecks;
|
||||
} catch (error) {
|
||||
error.service = SERVICE_NAME;
|
||||
|
||||
@@ -74,6 +74,11 @@ const deleteNotificationsByMonitorId = async (monitorId) => {
|
||||
|
||||
const deleteNotificationById = async (id) => {
|
||||
try {
|
||||
const notification = await Notification.findById(id);
|
||||
if (!notification) {
|
||||
throw new Error("Notification not found");
|
||||
}
|
||||
|
||||
const result = await Notification.findByIdAndDelete(id);
|
||||
await Monitor.updateMany({ notifications: id }, { $pull: { notifications: id } });
|
||||
return result;
|
||||
|
||||
@@ -29,9 +29,7 @@ const updateAppSettings = async (newSettings) => {
|
||||
await AppSettings.findOneAndUpdate({}, update, {
|
||||
upsert: true,
|
||||
});
|
||||
const settings = await AppSettings.findOne()
|
||||
.select("-__v -_id -createdAt -updatedAt -singleton")
|
||||
.lean();
|
||||
const settings = await AppSettings.findOne().select("-__v -_id -createdAt -updatedAt -singleton").lean();
|
||||
return settings;
|
||||
} catch (error) {
|
||||
error.service = SERVICE_NAME;
|
||||
|
||||
@@ -48,13 +48,9 @@ const updateStatusPage = async (statusPageData, image) => {
|
||||
if (statusPageData.deleteSubmonitors === "true") {
|
||||
statusPageData.subMonitors = [];
|
||||
}
|
||||
const statusPage = await StatusPage.findOneAndUpdate(
|
||||
{ url: statusPageData.url },
|
||||
statusPageData,
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
);
|
||||
const statusPage = await StatusPage.findOneAndUpdate({ url: statusPageData.url }, statusPageData, {
|
||||
new: true,
|
||||
});
|
||||
|
||||
return statusPage;
|
||||
} catch (error) {
|
||||
@@ -98,19 +94,8 @@ const getStatusPage = async (url) => {
|
||||
}
|
||||
|
||||
if (!preliminaryStatusPage.monitors || preliminaryStatusPage.monitors.length === 0) {
|
||||
const {
|
||||
_id,
|
||||
color,
|
||||
companyName,
|
||||
isPublished,
|
||||
logo,
|
||||
originalMonitors,
|
||||
showCharts,
|
||||
showUptimePercentage,
|
||||
timezone,
|
||||
showAdminLoginLink,
|
||||
url,
|
||||
} = preliminaryStatusPage;
|
||||
const { _id, color, companyName, isPublished, logo, originalMonitors, showCharts, showUptimePercentage, timezone, showAdminLoginLink, url } =
|
||||
preliminaryStatusPage;
|
||||
return {
|
||||
statusPage: {
|
||||
_id,
|
||||
|
||||
@@ -16,11 +16,7 @@ const SERVICE_NAME = "userModule";
|
||||
* @returns {Promise<UserModel>}
|
||||
* @throws {Error}
|
||||
*/
|
||||
const insertUser = async (
|
||||
userData,
|
||||
imageFile,
|
||||
generateAvatarImage = GenerateAvatarImage
|
||||
) => {
|
||||
const insertUser = async (userData, imageFile, generateAvatarImage = GenerateAvatarImage) => {
|
||||
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
|
||||
try {
|
||||
if (imageFile) {
|
||||
@@ -47,9 +43,7 @@ const insertUser = async (
|
||||
|
||||
const newUser = new UserModel(userData);
|
||||
await newUser.save();
|
||||
return await UserModel.findOne({ _id: newUser._id })
|
||||
.select("-password")
|
||||
.select("-profileImage"); // .select() doesn't work with create, need to save then find
|
||||
return await UserModel.findOne({ _id: newUser._id }).select("-password").select("-profileImage"); // .select() doesn't work with create, need to save then find
|
||||
} catch (error) {
|
||||
if (error.code === DUPLICATE_KEY_CODE) {
|
||||
error.message = stringService.dbUserExists;
|
||||
@@ -98,31 +92,26 @@ const getUserByEmail = async (email) => {
|
||||
* @throws {Error}
|
||||
*/
|
||||
|
||||
const updateUser = async (
|
||||
req,
|
||||
res,
|
||||
parseBoolean = ParseBoolean,
|
||||
generateAvatarImage = GenerateAvatarImage
|
||||
) => {
|
||||
const candidateUserId = req.params.userId;
|
||||
try {
|
||||
const candidateUser = { ...req.body };
|
||||
// ******************************************
|
||||
// Handle profile image
|
||||
// ******************************************
|
||||
const updateUser = async ({ userId, user, file }) => {
|
||||
if (!userId) {
|
||||
throw new Error("No user in request");
|
||||
}
|
||||
|
||||
if (parseBoolean(candidateUser.deleteProfileImage) === true) {
|
||||
try {
|
||||
const candidateUser = { ...user };
|
||||
|
||||
if (ParseBoolean(candidateUser.deleteProfileImage) === true) {
|
||||
candidateUser.profileImage = null;
|
||||
candidateUser.avatarImage = null;
|
||||
} else if (req.file) {
|
||||
} else if (file) {
|
||||
// 1. Save the full size image
|
||||
candidateUser.profileImage = {
|
||||
data: req.file.buffer,
|
||||
contentType: req.file.mimetype,
|
||||
data: file.buffer,
|
||||
contentType: file.mimetype,
|
||||
};
|
||||
|
||||
// 2. Get the avatar sized image
|
||||
const avatar = await generateAvatarImage(req.file);
|
||||
const avatar = await GenerateAvatarImage(file);
|
||||
candidateUser.avatarImage = avatar;
|
||||
}
|
||||
|
||||
@@ -131,7 +120,7 @@ const updateUser = async (
|
||||
// ******************************************
|
||||
|
||||
const updatedUser = await UserModel.findByIdAndUpdate(
|
||||
candidateUserId,
|
||||
userId,
|
||||
candidateUser,
|
||||
{ new: true } // Returns updated user instead of pre-update user
|
||||
)
|
||||
@@ -220,13 +209,33 @@ const logoutUser = async (userId) => {
|
||||
}
|
||||
};
|
||||
|
||||
export {
|
||||
insertUser,
|
||||
getUserByEmail,
|
||||
updateUser,
|
||||
deleteUser,
|
||||
deleteTeam,
|
||||
deleteAllOtherUsers,
|
||||
getAllUsers,
|
||||
logoutUser,
|
||||
const getUserById = async (roles, userId) => {
|
||||
try {
|
||||
if (!roles.includes("superadmin")) {
|
||||
throw new Error("User is not a superadmin");
|
||||
}
|
||||
|
||||
const user = await UserModel.findById(userId).select("-password").select("-profileImage");
|
||||
if (!user) {
|
||||
throw new Error("User not found");
|
||||
}
|
||||
|
||||
return user;
|
||||
} catch (error) {
|
||||
error.service = SERVICE_NAME;
|
||||
error.method = "getUserById";
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const editUserById = async (userId, user) => {
|
||||
try {
|
||||
await UserModel.findByIdAndUpdate(userId, user, { new: true }).select("-password").select("-profileImage");
|
||||
} catch (error) {
|
||||
error.service = SERVICE_NAME;
|
||||
error.method = "editUserById";
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export { insertUser, getUserByEmail, updateUser, deleteUser, deleteTeam, deleteAllOtherUsers, getAllUsers, logoutUser, getUserById, editUserById };
|
||||
+16
-44
@@ -102,9 +102,7 @@ const SHUTDOWN_TIMEOUT = 1000;
|
||||
let isShuttingDown = false;
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const openApiSpec = JSON.parse(
|
||||
fs.readFileSync(path.join(__dirname, "openapi.json"), "utf8")
|
||||
);
|
||||
const openApiSpec = JSON.parse(fs.readFileSync(path.join(__dirname, "openapi.json"), "utf8"));
|
||||
|
||||
const frontendPath = path.join(__dirname, "public");
|
||||
|
||||
@@ -159,25 +157,8 @@ const startApp = async () => {
|
||||
// Set allowed origin
|
||||
const allowedOrigin = appSettings.clientHost;
|
||||
|
||||
const networkService = new NetworkService(
|
||||
axios,
|
||||
ping,
|
||||
logger,
|
||||
http,
|
||||
Docker,
|
||||
net,
|
||||
stringService,
|
||||
settingsService
|
||||
);
|
||||
const emailService = new EmailService(
|
||||
settingsService,
|
||||
fs,
|
||||
path,
|
||||
compile,
|
||||
mjml2html,
|
||||
nodemailer,
|
||||
logger
|
||||
);
|
||||
const networkService = new NetworkService(axios, ping, logger, http, Docker, net, stringService, settingsService);
|
||||
const emailService = new EmailService(settingsService, fs, path, compile, mjml2html, nodemailer, logger);
|
||||
const bufferService = new BufferService({ db, logger });
|
||||
const statusService = new StatusService({ db, logger, buffer: bufferService });
|
||||
const notificationUtils = new NotificationUtils({
|
||||
@@ -310,17 +291,11 @@ const startApp = async () => {
|
||||
ServiceRegistry.get(StringService.SERVICE_NAME)
|
||||
);
|
||||
|
||||
const queueController = new QueueController(
|
||||
ServiceRegistry.get(JobQueue.SERVICE_NAME),
|
||||
ServiceRegistry.get(StringService.SERVICE_NAME)
|
||||
);
|
||||
const queueController = new QueueController(ServiceRegistry.get(JobQueue.SERVICE_NAME), ServiceRegistry.get(StringService.SERVICE_NAME));
|
||||
|
||||
const logController = new LogController(logger);
|
||||
|
||||
const statusPageController = new StatusPageController(
|
||||
ServiceRegistry.get(MongoDB.SERVICE_NAME),
|
||||
ServiceRegistry.get(StringService.SERVICE_NAME)
|
||||
);
|
||||
const statusPageController = new StatusPageController(ServiceRegistry.get(MongoDB.SERVICE_NAME), ServiceRegistry.get(StringService.SERVICE_NAME));
|
||||
|
||||
const notificationController = new NotificationController({
|
||||
notificationService: ServiceRegistry.get(NotificationService.SERVICE_NAME),
|
||||
@@ -329,9 +304,7 @@ const startApp = async () => {
|
||||
db: ServiceRegistry.get(MongoDB.SERVICE_NAME),
|
||||
});
|
||||
|
||||
const diagnosticController = new DiagnosticController(
|
||||
ServiceRegistry.get(MongoDB.SERVICE_NAME)
|
||||
);
|
||||
const diagnosticController = new DiagnosticController(ServiceRegistry.get(MongoDB.SERVICE_NAME));
|
||||
|
||||
//Create routes
|
||||
const authRoutes = new AuthRoutes(authController);
|
||||
@@ -339,9 +312,7 @@ const startApp = async () => {
|
||||
const settingsRoutes = new SettingsRoutes(settingsController);
|
||||
const checkRoutes = new CheckRoutes(checkController);
|
||||
const inviteRoutes = new InviteRoutes(inviteController);
|
||||
const maintenanceWindowRoutes = new MaintenanceWindowRoutes(
|
||||
maintenanceWindowController
|
||||
);
|
||||
const maintenanceWindowRoutes = new MaintenanceWindowRoutes(maintenanceWindowController);
|
||||
const queueRoutes = new QueueRoutes(queueController);
|
||||
const logRoutes = new LogRoutes(logController);
|
||||
const statusPageRoutes = new StatusPageRoutes(statusPageController);
|
||||
@@ -390,16 +361,17 @@ const startApp = async () => {
|
||||
|
||||
//routes
|
||||
app.use("/api/v1/auth", authRoutes.getRouter());
|
||||
app.use("/api/v1/settings", verifyJWT, settingsRoutes.getRouter());
|
||||
app.use("/api/v1/invite", inviteRoutes.getRouter());
|
||||
app.use("/api/v1/monitors", verifyJWT, monitorRoutes.getRouter());
|
||||
app.use("/api/v1/checks", verifyJWT, checkRoutes.getRouter());
|
||||
app.use("/api/v1/maintenance-window", verifyJWT, maintenanceWindowRoutes.getRouter());
|
||||
app.use("/api/v1/queue", verifyJWT, queueRoutes.getRouter());
|
||||
app.use("/api/v1/logs", verifyJWT, logRoutes.getRouter());
|
||||
app.use("/api/v1/status-page", statusPageRoutes.getRouter());
|
||||
app.use("/api/v1/notifications", verifyJWT, notificationRoutes.getRouter());
|
||||
app.use("/api/v1/diagnostic", verifyJWT, diagnosticRoutes.getRouter());
|
||||
app.use("/api/v1/invite", inviteRoutes.getRouter());
|
||||
app.use("/api/v1/logs", verifyJWT, logRoutes.getRouter());
|
||||
app.use("/api/v1/maintenance-window", verifyJWT, maintenanceWindowRoutes.getRouter());
|
||||
app.use("/api/v1/monitors", verifyJWT, monitorRoutes.getRouter());
|
||||
app.use("/api/v1/notifications", verifyJWT, notificationRoutes.getRouter());
|
||||
app.use("/api/v1/queue", verifyJWT, queueRoutes.getRouter());
|
||||
app.use("/api/v1/settings", verifyJWT, settingsRoutes.getRouter());
|
||||
app.use("/api/v1/status-page", statusPageRoutes.getRouter());
|
||||
|
||||
app.use("/api/v1/health", (req, res) => {
|
||||
res.json({
|
||||
status: "OK",
|
||||
|
||||
@@ -3,6 +3,7 @@ import ServiceRegistry from "../service/serviceRegistry.js";
|
||||
import StringService from "../service/stringService.js";
|
||||
|
||||
const handleErrors = (error, req, res, next) => {
|
||||
console.log("ERROR", error);
|
||||
const status = error.status || 500;
|
||||
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
|
||||
const message = error.message || stringService.authIncorrectPassword;
|
||||
|
||||
@@ -29,9 +29,7 @@ const isAllowed = (allowedRoles) => {
|
||||
// Parse the token
|
||||
try {
|
||||
const parsedToken = token.slice(TOKEN_PREFIX.length, token.length);
|
||||
const { jwtSecret } = ServiceRegistry.get(
|
||||
SettingsService.SERVICE_NAME
|
||||
).getSettings();
|
||||
const { jwtSecret } = ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings();
|
||||
var decoded = jwt.verify(parsedToken, jwtSecret);
|
||||
const userRoles = decoded.role;
|
||||
|
||||
|
||||
@@ -1,28 +1,27 @@
|
||||
import logger from "../utils/logger.js";
|
||||
|
||||
const languageMiddleware =
|
||||
(stringService, translationService) => async (req, res, next) => {
|
||||
try {
|
||||
const acceptLanguage = req.headers["accept-language"] || "en";
|
||||
const language = acceptLanguage.split(",")[0].slice(0, 2).toLowerCase();
|
||||
const languageMiddleware = (stringService, translationService) => async (req, res, next) => {
|
||||
try {
|
||||
const acceptLanguage = req.headers["accept-language"] || "en";
|
||||
const language = acceptLanguage.split(",")[0].slice(0, 2).toLowerCase();
|
||||
|
||||
translationService.setLanguage(language);
|
||||
stringService.setLanguage(language);
|
||||
translationService.setLanguage(language);
|
||||
stringService.setLanguage(language);
|
||||
|
||||
next();
|
||||
} catch (error) {
|
||||
logger.error({
|
||||
message: error.message,
|
||||
service: "languageMiddleware",
|
||||
});
|
||||
const acceptLanguage = req.headers["accept-language"] || "en";
|
||||
const language = acceptLanguage.split(",")[0].slice(0, 2).toLowerCase();
|
||||
next();
|
||||
} catch (error) {
|
||||
logger.error({
|
||||
message: error.message,
|
||||
service: "languageMiddleware",
|
||||
});
|
||||
const acceptLanguage = req.headers["accept-language"] || "en";
|
||||
const language = acceptLanguage.split(",")[0].slice(0, 2).toLowerCase();
|
||||
|
||||
translationService.setLanguage(language);
|
||||
stringService.setLanguage(language);
|
||||
translationService.setLanguage(language);
|
||||
stringService.setLanguage(language);
|
||||
|
||||
next();
|
||||
}
|
||||
};
|
||||
next();
|
||||
}
|
||||
};
|
||||
|
||||
export default languageMiddleware;
|
||||
@@ -39,13 +39,13 @@ const verifyJWT = (req, res, next) => {
|
||||
const { jwtSecret } = ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings();
|
||||
jwt.verify(parsedToken, jwtSecret, (err, decoded) => {
|
||||
if (err) {
|
||||
if (err) {
|
||||
const errorMessage =
|
||||
err.name === "TokenExpiredError"
|
||||
? stringService.expiredAuthToken
|
||||
: stringService.invalidAuthToken;
|
||||
return res.status(401).json({ success: false, msg: errorMessage });
|
||||
}
|
||||
const errorMessage = err.name === "TokenExpiredError" ? stringService.expiredAuthToken : stringService.invalidAuthToken;
|
||||
err.details = { msg: errorMessage };
|
||||
err.status = 401;
|
||||
err.service = SERVICE_NAME;
|
||||
err.method = "verifyJWT";
|
||||
next(err);
|
||||
return;
|
||||
} else {
|
||||
// Token is valid, carry on
|
||||
req.user = decoded;
|
||||
|
||||
@@ -47,9 +47,7 @@ const verifySuperAdmin = (req, res, next) => {
|
||||
stack: err.stack,
|
||||
details: stringService.invalidAuthToken,
|
||||
});
|
||||
return res
|
||||
.status(401)
|
||||
.json({ success: false, msg: stringService.invalidAuthToken });
|
||||
return res.status(401).json({ success: false, msg: stringService.invalidAuthToken });
|
||||
}
|
||||
|
||||
if (decoded.role.includes("superadmin") === false) {
|
||||
|
||||
+1
-8
@@ -100,14 +100,7 @@
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"firstName",
|
||||
"lastName",
|
||||
"email",
|
||||
"password",
|
||||
"role",
|
||||
"teamId"
|
||||
],
|
||||
"required": ["firstName", "lastName", "email", "password", "role", "teamId"],
|
||||
"properties": {
|
||||
"firstName": {
|
||||
"type": "string"
|
||||
|
||||
@@ -15,12 +15,7 @@ class AnnouncementRoutes {
|
||||
* @desc Create a new announcement
|
||||
* @access Private (Requires JWT verification)
|
||||
*/
|
||||
this.router.post(
|
||||
"/",
|
||||
verifyJWT,
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.announcementController.createAnnouncement
|
||||
);
|
||||
this.router.post("/", verifyJWT, isAllowed(["admin", "superadmin"]), this.announcementController.createAnnouncement);
|
||||
|
||||
/**
|
||||
* @route GET /
|
||||
|
||||
+10
-29
@@ -15,40 +15,21 @@ class AuthRoutes {
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
this.router.post(
|
||||
"/register",
|
||||
upload.single("profileImage"),
|
||||
this.authController.registerUser
|
||||
);
|
||||
this.router.post("/register", upload.single("profileImage"), this.authController.registerUser);
|
||||
this.router.post("/login", this.authController.loginUser);
|
||||
|
||||
this.router.put(
|
||||
"/user/:userId",
|
||||
upload.single("profileImage"),
|
||||
verifyJWT,
|
||||
this.authController.editUser
|
||||
);
|
||||
|
||||
this.router.get("/users/superadmin", this.authController.checkSuperadminExists);
|
||||
|
||||
this.router.get(
|
||||
"/users",
|
||||
verifyJWT,
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.authController.getAllUsers
|
||||
);
|
||||
|
||||
this.router.delete(
|
||||
"/user/:userId",
|
||||
verifyJWT,
|
||||
verifyOwnership(User, "userId"),
|
||||
this.authController.deleteUser
|
||||
);
|
||||
|
||||
// Recovery routes
|
||||
this.router.post("/recovery/request", this.authController.requestRecovery);
|
||||
this.router.post("/recovery/validate", this.authController.validateRecovery);
|
||||
this.router.post("/recovery/reset/", this.authController.resetPassword);
|
||||
|
||||
this.router.get("/users/superadmin", this.authController.checkSuperadminExists);
|
||||
|
||||
this.router.get("/users", verifyJWT, isAllowed(["admin", "superadmin"]), this.authController.getAllUsers);
|
||||
this.router.get("/users/:userId", verifyJWT, isAllowed(["superadmin"]), this.authController.getUserById);
|
||||
this.router.put("/users/:userId", verifyJWT, isAllowed(["superadmin"]), this.authController.editUserById);
|
||||
|
||||
this.router.put("/user", verifyJWT, upload.single("profileImage"), this.authController.editUser);
|
||||
this.router.delete("/user", verifyJWT, this.authController.deleteUser);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
|
||||
@@ -13,40 +13,17 @@ class CheckRoutes {
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
this.router.get("/team", this.checkController.getChecksByTeam);
|
||||
this.router.get("/team/summary", this.checkController.getChecksSummaryByTeamId);
|
||||
this.router.delete(
|
||||
"/team",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.checkController.deleteChecksByTeamId
|
||||
);
|
||||
this.router.get("/team", this.checkController.getChecksByTeam);
|
||||
this.router.put("/team/ttl", isAllowed(["admin", "superadmin"]), this.checkController.updateChecksTTL);
|
||||
this.router.delete("/team", isAllowed(["admin", "superadmin"]), this.checkController.deleteChecksByTeamId);
|
||||
|
||||
this.router.put("/check/:checkId", this.checkController.ackCheck);
|
||||
|
||||
this.router.get("/:monitorId", this.checkController.getChecksByMonitor);
|
||||
|
||||
this.router.put(
|
||||
"/check/:checkId",
|
||||
verifyTeamAccess(Check, "checkId"),
|
||||
this.checkController.ackCheck
|
||||
);
|
||||
this.router.delete("/:monitorId", this.checkController.deleteChecks);
|
||||
|
||||
this.router.put("/:path/:monitorId?", this.checkController.ackAllChecks);
|
||||
|
||||
this.router.post(
|
||||
"/:monitorId",
|
||||
verifyOwnership(Monitor, "monitorId"),
|
||||
this.checkController.createCheck
|
||||
);
|
||||
this.router.delete(
|
||||
"/:monitorId",
|
||||
verifyOwnership(Monitor, "monitorId"),
|
||||
this.checkController.deleteChecks
|
||||
);
|
||||
|
||||
this.router.put(
|
||||
"/team/ttl",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.checkController.updateChecksTTL
|
||||
);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Router } from "express";
|
||||
import { verifyJWT } from "../middleware/verifyJWT.js";
|
||||
import { isAllowed } from "../middleware/isAllowed.js";
|
||||
|
||||
class DiagnosticRoutes {
|
||||
constructor(diagnosticController) {
|
||||
@@ -7,12 +9,7 @@ class DiagnosticRoutes {
|
||||
this.initRoutes();
|
||||
}
|
||||
initRoutes() {
|
||||
this.router.get(
|
||||
"/db/get-monitors-by-team-id/:teamId",
|
||||
this.diagnosticController.getMonitorsByTeamIdExecutionStats
|
||||
);
|
||||
|
||||
this.router.post("/db/stats", this.diagnosticController.getDbStats);
|
||||
this.router.get("/system", verifyJWT, isAllowed(["admin", "superadmin"]), this.diagnosticController.getSystemStats);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
|
||||
@@ -10,15 +10,9 @@ class InviteRoutes {
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
this.router.post(
|
||||
"/",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
verifyJWT,
|
||||
this.inviteController.getInviteToken
|
||||
);
|
||||
|
||||
this.router.post("/send", this.inviteController.sendInviteEmail);
|
||||
this.router.post("/verify", this.inviteController.inviteVerifyController);
|
||||
this.router.post("/", verifyJWT, isAllowed(["admin", "superadmin"]), this.inviteController.getInviteToken);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
|
||||
@@ -1,41 +1,20 @@
|
||||
import { Router } from "express";
|
||||
import { verifyOwnership } from "../middleware/verifyOwnership.js";
|
||||
import { verifyTeamAccess } from "../middleware/verifyTeamAccess.js";
|
||||
import Monitor from "../db/models/Monitor.js";
|
||||
import MaintenanceWindow from "../db/models/MaintenanceWindow.js";
|
||||
class MaintenanceWindowRoutes {
|
||||
constructor(maintenanceWindowController) {
|
||||
this.router = Router();
|
||||
this.maintenanceWindowController = maintenanceWindowController;
|
||||
this.mwController = maintenanceWindowController;
|
||||
this.initRoutes();
|
||||
}
|
||||
initRoutes() {
|
||||
this.router.post("/", this.maintenanceWindowController.createMaintenanceWindows);
|
||||
this.router.post("/", this.mwController.createMaintenanceWindows);
|
||||
this.router.get("/team/", this.mwController.getMaintenanceWindowsByTeamId);
|
||||
|
||||
this.router.get(
|
||||
"/monitor/:monitorId",
|
||||
verifyOwnership(Monitor, "monitorId"),
|
||||
this.maintenanceWindowController.getMaintenanceWindowsByMonitorId
|
||||
);
|
||||
this.router.get("/monitor/:monitorId", this.mwController.getMaintenanceWindowsByMonitorId);
|
||||
|
||||
this.router.get(
|
||||
"/team/",
|
||||
this.maintenanceWindowController.getMaintenanceWindowsByTeamId
|
||||
);
|
||||
|
||||
this.router.get("/:id", this.maintenanceWindowController.getMaintenanceWindowById);
|
||||
|
||||
this.router.put(
|
||||
"/:id",
|
||||
verifyTeamAccess(MaintenanceWindow, "id"),
|
||||
this.maintenanceWindowController.editMaintenanceWindow
|
||||
);
|
||||
|
||||
this.router.delete(
|
||||
"/:id",
|
||||
verifyTeamAccess(MaintenanceWindow, "id"),
|
||||
this.maintenanceWindowController.deleteMaintenanceWindow
|
||||
);
|
||||
this.router.get("/:id", this.mwController.getMaintenanceWindowById);
|
||||
this.router.put("/:id", this.mwController.editMaintenanceWindow);
|
||||
this.router.delete("/:id", this.mwController.deleteMaintenanceWindow);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
|
||||
@@ -17,103 +17,43 @@ class MonitorRoutes {
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
this.router.get("/", this.monitorController.getAllMonitors);
|
||||
this.router.get("/uptime", this.monitorController.getAllMonitorsWithUptimeStats);
|
||||
this.router.get(
|
||||
"/export",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.monitorController.exportMonitorsToCSV
|
||||
);
|
||||
this.router.get("/stats/:monitorId", this.monitorController.getMonitorStatsById);
|
||||
this.router.get(
|
||||
"/hardware/details/:monitorId",
|
||||
this.monitorController.getHardwareDetailsById
|
||||
);
|
||||
|
||||
this.router.get(
|
||||
"/uptime/details/:monitorId",
|
||||
this.monitorController.getUptimeDetailsById
|
||||
);
|
||||
this.router.get("/certificate/:monitorId", (req, res, next) => {
|
||||
this.monitorController.getMonitorCertificate(
|
||||
req,
|
||||
res,
|
||||
next,
|
||||
fetchMonitorCertificate
|
||||
);
|
||||
});
|
||||
// Team routes
|
||||
this.router.get("/team", this.monitorController.getMonitorsByTeamId);
|
||||
this.router.get("/team/with-checks", this.monitorController.getMonitorsWithChecksByTeamId);
|
||||
this.router.get("/team/summary", this.monitorController.getMonitorsAndSummaryByTeamId);
|
||||
|
||||
this.router.get("/:monitorId", this.monitorController.getMonitorById);
|
||||
// Uptime routes
|
||||
this.router.get("/uptime/details/:monitorId", this.monitorController.getUptimeDetailsById);
|
||||
|
||||
this.router.get(
|
||||
"/summary/team",
|
||||
this.monitorController.getMonitorsAndSummaryByTeamId
|
||||
);
|
||||
// Hardware routes
|
||||
this.router.get("/hardware/details/:monitorId", this.monitorController.getHardwareDetailsById);
|
||||
|
||||
this.router.get(
|
||||
"/team/with-checks",
|
||||
this.monitorController.getMonitorsWithChecksByTeamId
|
||||
);
|
||||
// General monitor routes
|
||||
this.router.post("/pause/:monitorId", isAllowed(["admin", "superadmin"]), this.monitorController.pauseMonitor);
|
||||
this.router.get("/stats/:monitorId", this.monitorController.getMonitorStatsById);
|
||||
|
||||
this.router.get(
|
||||
"/resolution/url",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.monitorController.checkEndpointResolution
|
||||
);
|
||||
// Util routes
|
||||
this.router.get("/resolution/url", isAllowed(["admin", "superadmin"]), this.monitorController.checkEndpointResolution);
|
||||
this.router.get("/certificate/:monitorId", (req, res, next) => {
|
||||
this.monitorController.getMonitorCertificate(req, res, next, fetchMonitorCertificate);
|
||||
});
|
||||
|
||||
this.router.delete(
|
||||
"/:monitorId",
|
||||
verifyOwnership(Monitor, "monitorId"),
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.monitorController.deleteMonitor
|
||||
);
|
||||
|
||||
this.router.post(
|
||||
"/",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.monitorController.createMonitor
|
||||
);
|
||||
|
||||
this.router.put(
|
||||
"/:monitorId",
|
||||
verifyTeamAccess(Monitor, "monitorId"),
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.monitorController.editMonitor
|
||||
);
|
||||
|
||||
this.router.delete(
|
||||
"/",
|
||||
isAllowed(["superadmin"]),
|
||||
this.monitorController.deleteAllMonitors
|
||||
);
|
||||
|
||||
this.router.post(
|
||||
"/pause/:monitorId",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.monitorController.pauseMonitor
|
||||
);
|
||||
|
||||
this.router.post(
|
||||
"/demo",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.monitorController.addDemoMonitors
|
||||
);
|
||||
|
||||
this.router.post(
|
||||
"/bulk",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
upload.single("csvFile"),
|
||||
this.monitorController.createBulkMonitors
|
||||
);
|
||||
// General monitor CRUD routes
|
||||
this.router.get("/", this.monitorController.getAllMonitors);
|
||||
this.router.post("/", isAllowed(["admin", "superadmin"]), this.monitorController.createMonitor);
|
||||
this.router.delete("/", isAllowed(["superadmin"]), this.monitorController.deleteAllMonitors);
|
||||
|
||||
// Other static routes
|
||||
this.router.post("/demo", isAllowed(["admin", "superadmin"]), this.monitorController.addDemoMonitors);
|
||||
this.router.get("/export", isAllowed(["admin", "superadmin"]), this.monitorController.exportMonitorsToCSV);
|
||||
this.router.post("/seed", isAllowed(["superadmin"]), this.monitorController.seedDb);
|
||||
this.router.post("/bulk", isAllowed(["admin", "superadmin"]), upload.single("csvFile"), this.monitorController.createBulkMonitors);
|
||||
this.router.post("/test-email", isAllowed(["admin", "superadmin"]), this.monitorController.sendTestEmail);
|
||||
|
||||
this.router.post(
|
||||
"/test-email",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.monitorController.sendTestEmail
|
||||
);
|
||||
// Individual monitor CRUD routes
|
||||
this.router.get("/:monitorId", this.monitorController.getMonitorById);
|
||||
this.router.put("/:monitorId", isAllowed(["admin", "superadmin"]), this.monitorController.editMonitor);
|
||||
this.router.delete("/:monitorId", isAllowed(["admin", "superadmin"]), this.monitorController.deleteMonitor);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import { Router } from "express";
|
||||
import { verifyJWT } from "../middleware/verifyJWT.js";
|
||||
import { verifyOwnership } from "../middleware/verifyOwnership.js";
|
||||
import { verifyTeamAccess } from "../middleware/verifyTeamAccess.js";
|
||||
import Notification from "../db/models/Notification.js";
|
||||
class NotificationRoutes {
|
||||
constructor(notificationController) {
|
||||
this.router = Router();
|
||||
@@ -11,27 +7,16 @@ class NotificationRoutes {
|
||||
}
|
||||
|
||||
initializeRoutes() {
|
||||
this.router.use(verifyJWT);
|
||||
|
||||
this.router.post("/test", this.notificationController.testNotification);
|
||||
this.router.post("/test/all", this.notificationController.testAllNotifications);
|
||||
|
||||
this.router.post("/", this.notificationController.createNotification);
|
||||
|
||||
this.router.post("/test/all", this.notificationController.testAllNotifications);
|
||||
this.router.post("/test", this.notificationController.testNotification);
|
||||
|
||||
this.router.get("/team", this.notificationController.getNotificationsByTeamId);
|
||||
|
||||
this.router.delete(
|
||||
"/:id",
|
||||
verifyOwnership(Notification, "id"),
|
||||
this.notificationController.deleteNotification
|
||||
);
|
||||
|
||||
this.router.get("/:id", this.notificationController.getNotificationById);
|
||||
this.router.put(
|
||||
"/:id",
|
||||
verifyTeamAccess(Notification, "id"),
|
||||
this.notificationController.editNotification
|
||||
);
|
||||
this.router.delete("/:id", this.notificationController.deleteNotification);
|
||||
this.router.put("/:id", this.notificationController.editNotification);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
|
||||
@@ -7,41 +7,13 @@ class QueueRoutes {
|
||||
this.initRoutes();
|
||||
}
|
||||
initRoutes() {
|
||||
this.router.get(
|
||||
"/metrics",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.queueController.getMetrics
|
||||
);
|
||||
this.router.get("/jobs", isAllowed(["admin", "superadmin"]), this.queueController.getJobs);
|
||||
this.router.post("/jobs", isAllowed(["admin", "superadmin"]), this.queueController.addJob);
|
||||
|
||||
this.router.get(
|
||||
"/jobs",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.queueController.getJobs
|
||||
);
|
||||
|
||||
this.router.get(
|
||||
"/all-metrics",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.queueController.getAllMetrics
|
||||
);
|
||||
|
||||
this.router.post(
|
||||
"/jobs",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.queueController.addJob
|
||||
);
|
||||
|
||||
this.router.post(
|
||||
"/flush",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.queueController.flushQueue
|
||||
);
|
||||
|
||||
this.router.get(
|
||||
"/health",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.queueController.checkQueueHealth
|
||||
);
|
||||
this.router.get("/metrics", isAllowed(["admin", "superadmin"]), this.queueController.getMetrics);
|
||||
this.router.get("/health", isAllowed(["admin", "superadmin"]), this.queueController.checkQueueHealth);
|
||||
this.router.get("/all-metrics", isAllowed(["admin", "superadmin"]), this.queueController.getAllMetrics);
|
||||
this.router.post("/flush", isAllowed(["admin", "superadmin"]), this.queueController.flushQueue);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
|
||||
@@ -10,16 +10,8 @@ class SettingsRoutes {
|
||||
|
||||
initRoutes() {
|
||||
this.router.get("/", this.settingsController.getAppSettings);
|
||||
this.router.put(
|
||||
"/",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.settingsController.updateAppSettings
|
||||
);
|
||||
this.router.post(
|
||||
"/test-email",
|
||||
isAllowed(["admin", "superadmin"]),
|
||||
this.settingsController.sendTestEmail
|
||||
);
|
||||
this.router.put("/", isAllowed(["admin", "superadmin"]), this.settingsController.updateAppSettings);
|
||||
this.router.post("/test-email", isAllowed(["admin", "superadmin"]), this.settingsController.sendTestEmail);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
|
||||
@@ -13,20 +13,11 @@ class StatusPageRoutes {
|
||||
initRoutes() {
|
||||
this.router.get("/", this.statusPageController.getStatusPage);
|
||||
this.router.get("/team", verifyJWT, this.statusPageController.getStatusPagesByTeamId);
|
||||
this.router.get("/:url", this.statusPageController.getStatusPageByUrl);
|
||||
|
||||
this.router.post(
|
||||
"/",
|
||||
upload.single("logo"),
|
||||
verifyJWT,
|
||||
this.statusPageController.createStatusPage
|
||||
);
|
||||
this.router.put(
|
||||
"/",
|
||||
upload.single("logo"),
|
||||
verifyJWT,
|
||||
this.statusPageController.updateStatusPage
|
||||
);
|
||||
this.router.post("/", upload.single("logo"), verifyJWT, this.statusPageController.createStatusPage);
|
||||
this.router.put("/", upload.single("logo"), verifyJWT, this.statusPageController.updateStatusPage);
|
||||
|
||||
this.router.get("/:url", this.statusPageController.getStatusPageByUrl);
|
||||
this.router.delete("/:url(*)", verifyJWT, this.statusPageController.deleteStatusPage);
|
||||
}
|
||||
|
||||
|
||||
@@ -150,11 +150,7 @@ class JobQueue {
|
||||
};
|
||||
|
||||
const schedulerId = getSchedulerId(monitor);
|
||||
await queue.upsertJobScheduler(
|
||||
schedulerId,
|
||||
{ every: monitor?.interval ?? 60000 },
|
||||
jobTemplate
|
||||
);
|
||||
await queue.upsertJobScheduler(schedulerId, { every: monitor?.interval ?? 60000 }, jobTemplate);
|
||||
}
|
||||
|
||||
async deleteJob(monitor) {
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
const SERVICE_NAME = "JobQueueHelper";
|
||||
|
||||
class JobQueueHelper {
|
||||
constructor({
|
||||
redisService,
|
||||
Queue,
|
||||
Worker,
|
||||
logger,
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
}) {
|
||||
constructor({ redisService, Queue, Worker, logger, db, networkService, statusService, notificationService }) {
|
||||
this.db = db;
|
||||
this.redisService = redisService;
|
||||
this.Queue = Queue;
|
||||
@@ -265,11 +256,7 @@ class JobQueueHelper {
|
||||
|
||||
// Handle status change
|
||||
await job.updateProgress(60);
|
||||
const {
|
||||
monitor: updatedMonitor,
|
||||
statusChanged,
|
||||
prevStatus,
|
||||
} = await this.statusService.updateStatus(networkResponse);
|
||||
const { monitor: updatedMonitor, statusChanged, prevStatus } = await this.statusService.updateStatus(networkResponse);
|
||||
// Handle notifications
|
||||
await job.updateProgress(80);
|
||||
this.notificationService
|
||||
|
||||
@@ -22,8 +22,7 @@ class PulseQueue {
|
||||
// ****************************************
|
||||
init = async () => {
|
||||
try {
|
||||
const mongoConnectionString =
|
||||
this.appSettings.dbConnectionString || "mongodb://localhost:27017/uptime_db";
|
||||
const mongoConnectionString = this.appSettings.dbConnectionString || "mongodb://localhost:27017/uptime_db";
|
||||
this.pulse = new Pulse({ db: { address: mongoConnectionString } });
|
||||
await this.pulse.start();
|
||||
this.pulse.define("monitor-job", this.pulseQueueHelper.getMonitorJob(), {});
|
||||
@@ -186,9 +185,7 @@ class PulseQueue {
|
||||
failReason: job.attrs.failReason,
|
||||
lastRunAt: job.attrs.lastRunAt,
|
||||
lastFinishedAt: job.attrs.lastFinishedAt,
|
||||
lastRunTook: job.attrs.lockedAt
|
||||
? null
|
||||
: job.attrs.lastFinishedAt - job.attrs.lastRunAt,
|
||||
lastRunTook: job.attrs.lockedAt ? null : job.attrs.lastFinishedAt - job.attrs.lastRunAt,
|
||||
lastFailedAt: job.attrs.failedAt,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -34,11 +34,7 @@ class PulseQueueHelper {
|
||||
throw new Error("No network response");
|
||||
}
|
||||
|
||||
const {
|
||||
monitor: updatedMonitor,
|
||||
statusChanged,
|
||||
prevStatus,
|
||||
} = await this.statusService.updateStatus(networkResponse);
|
||||
const { monitor: updatedMonitor, statusChanged, prevStatus } = await this.statusService.updateStatus(networkResponse);
|
||||
|
||||
this.notificationService
|
||||
.handleNotifications({
|
||||
|
||||
@@ -42,10 +42,7 @@ class EmailService {
|
||||
*/
|
||||
this.loadTemplate = (templateName) => {
|
||||
try {
|
||||
const templatePath = this.path.join(
|
||||
__dirname,
|
||||
`../templates/${templateName}.mjml`
|
||||
);
|
||||
const templatePath = this.path.join(__dirname, `../templates/${templateName}.mjml`);
|
||||
const templateContent = this.fs.readFileSync(templatePath, "utf8");
|
||||
return this.compile(templateContent);
|
||||
} catch (error) {
|
||||
|
||||
@@ -78,9 +78,7 @@ class NetworkService {
|
||||
async requestPing(monitor) {
|
||||
try {
|
||||
const url = monitor.url;
|
||||
const { response, responseTime, error } = await this.timeRequest(() =>
|
||||
this.ping.promise.probe(url)
|
||||
);
|
||||
const { response, responseTime, error } = await this.timeRequest(() => this.ping.promise.probe(url));
|
||||
|
||||
const pingResponse = {
|
||||
monitorId: monitor._id,
|
||||
@@ -133,18 +131,7 @@ class NetworkService {
|
||||
*/
|
||||
async requestHttp(monitor) {
|
||||
try {
|
||||
const {
|
||||
url,
|
||||
secret,
|
||||
_id,
|
||||
name,
|
||||
teamId,
|
||||
type,
|
||||
ignoreTlsErrors,
|
||||
jsonPath,
|
||||
matchMethod,
|
||||
expectedValue,
|
||||
} = monitor;
|
||||
const { url, secret, _id, name, teamId, type, ignoreTlsErrors, jsonPath, matchMethod, expectedValue } = monitor;
|
||||
const config = {};
|
||||
|
||||
secret !== undefined && (config.headers = { Authorization: `Bearer ${secret}` });
|
||||
@@ -155,9 +142,7 @@ class NetworkService {
|
||||
});
|
||||
}
|
||||
|
||||
const { response, responseTime, error } = await this.timeRequest(() =>
|
||||
this.axios.get(url, config)
|
||||
);
|
||||
const { response, responseTime, error } = await this.timeRequest(() => this.axios.get(url, config));
|
||||
|
||||
const httpResponse = {
|
||||
monitorId: _id,
|
||||
@@ -171,8 +156,7 @@ class NetworkService {
|
||||
const code = error.response?.status || this.NETWORK_ERROR;
|
||||
httpResponse.code = code;
|
||||
httpResponse.status = false;
|
||||
httpResponse.message =
|
||||
this.http.STATUS_CODES[code] || this.stringService.httpNetworkError;
|
||||
httpResponse.message = this.http.STATUS_CODES[code] || this.stringService.httpNetworkError;
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
@@ -227,9 +211,7 @@ class NetworkService {
|
||||
else match = result === expectedValue;
|
||||
|
||||
httpResponse.status = match;
|
||||
httpResponse.message = match
|
||||
? this.stringService.httpMatchSuccess
|
||||
: this.stringService.httpMatchFail;
|
||||
httpResponse.message = match ? this.stringService.httpMatchSuccess : this.stringService.httpMatchFail;
|
||||
return httpResponse;
|
||||
} catch (error) {
|
||||
error.service = this.SERVICE_NAME;
|
||||
@@ -320,9 +302,7 @@ class NetworkService {
|
||||
}
|
||||
const container = docker.getContainer(monitor.url);
|
||||
|
||||
const { response, responseTime, error } = await this.timeRequest(() =>
|
||||
container.inspect()
|
||||
);
|
||||
const { response, responseTime, error } = await this.timeRequest(() => container.inspect());
|
||||
|
||||
const dockerResponse = {
|
||||
monitorId: monitor._id,
|
||||
@@ -333,8 +313,7 @@ class NetworkService {
|
||||
if (error) {
|
||||
dockerResponse.status = false;
|
||||
dockerResponse.code = error.statusCode || this.NETWORK_ERROR;
|
||||
dockerResponse.message =
|
||||
error.reason || "Failed to fetch Docker container information";
|
||||
dockerResponse.message = error.reason || "Failed to fetch Docker container information";
|
||||
return dockerResponse;
|
||||
}
|
||||
dockerResponse.status = response?.State?.Status === "running" ? true : false;
|
||||
|
||||
@@ -3,14 +3,7 @@ const SERVICE_NAME = "NotificationService";
|
||||
class NotificationService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
constructor({
|
||||
emailService,
|
||||
db,
|
||||
logger,
|
||||
networkService,
|
||||
stringService,
|
||||
notificationUtils,
|
||||
}) {
|
||||
constructor({ emailService, db, logger, networkService, stringService, notificationUtils }) {
|
||||
this.emailService = emailService;
|
||||
this.db = db;
|
||||
this.logger = logger;
|
||||
@@ -69,20 +62,15 @@ class NotificationService {
|
||||
const alerts = await this.notificationUtils.buildHardwareAlerts(networkResponse);
|
||||
if (alerts.length === 0) return false;
|
||||
|
||||
const { subject, html } = await this.notificationUtils.buildHardwareEmail(
|
||||
networkResponse,
|
||||
alerts
|
||||
);
|
||||
const content =
|
||||
await this.notificationUtils.buildHardwareNotificationMessage(alerts);
|
||||
const { subject, html } = await this.notificationUtils.buildHardwareEmail(networkResponse, alerts);
|
||||
const content = await this.notificationUtils.buildHardwareNotificationMessage(alerts);
|
||||
|
||||
const success = await this.notifyAll({ notificationIDs, subject, html, content });
|
||||
return success;
|
||||
}
|
||||
|
||||
// Status monitors
|
||||
const { subject, html } =
|
||||
await this.notificationUtils.buildStatusEmail(networkResponse);
|
||||
const { subject, html } = await this.notificationUtils.buildStatusEmail(networkResponse);
|
||||
const content = await this.notificationUtils.buildWebhookMessage(networkResponse);
|
||||
const success = this.notifyAll({ notificationIDs, subject, html, content });
|
||||
return success;
|
||||
|
||||
@@ -26,10 +26,7 @@ class NotificationUtils {
|
||||
const date = new Date(timestamp);
|
||||
|
||||
// Get timezone abbreviation and format the date
|
||||
const timeZoneAbbr = date
|
||||
.toLocaleTimeString("en-US", { timeZoneName: "short" })
|
||||
.split(" ")
|
||||
.pop();
|
||||
const timeZoneAbbr = date.toLocaleTimeString("en-US", { timeZoneName: "short" }).split(" ").pop();
|
||||
|
||||
// Format the date with readable format
|
||||
return (
|
||||
@@ -50,9 +47,7 @@ class NotificationUtils {
|
||||
};
|
||||
|
||||
// Get formatted time
|
||||
const formattedTime = timestamp
|
||||
? formatTime(timestamp)
|
||||
: formatTime(new Date().getTime());
|
||||
const formattedTime = timestamp ? formatTime(timestamp) : formatTime(new Date().getTime());
|
||||
|
||||
// Create different messages based on status with extra spacing
|
||||
let messageText;
|
||||
@@ -73,29 +68,15 @@ class NotificationUtils {
|
||||
buildHardwareAlerts = async (networkResponse) => {
|
||||
const monitor = networkResponse?.monitor;
|
||||
const thresholds = networkResponse?.monitor?.thresholds;
|
||||
const {
|
||||
usage_cpu: cpuThreshold = -1,
|
||||
usage_memory: memoryThreshold = -1,
|
||||
usage_disk: diskThreshold = -1,
|
||||
} = thresholds;
|
||||
const { usage_cpu: cpuThreshold = -1, usage_memory: memoryThreshold = -1, usage_disk: diskThreshold = -1 } = thresholds;
|
||||
|
||||
const metrics = networkResponse?.payload?.data;
|
||||
const {
|
||||
cpu: { usage_percent: cpuUsage = -1 } = {},
|
||||
memory: { usage_percent: memoryUsage = -1 } = {},
|
||||
disk = [],
|
||||
} = metrics;
|
||||
const { cpu: { usage_percent: cpuUsage = -1 } = {}, memory: { usage_percent: memoryUsage = -1 } = {}, disk = [] } = metrics;
|
||||
|
||||
const alerts = {
|
||||
cpu: cpuThreshold !== -1 && cpuUsage > cpuThreshold ? true : false,
|
||||
memory: memoryThreshold !== -1 && memoryUsage > memoryThreshold ? true : false,
|
||||
disk:
|
||||
disk?.some(
|
||||
(d) =>
|
||||
diskThreshold !== -1 &&
|
||||
typeof d?.usage_percent === "number" &&
|
||||
d?.usage_percent > diskThreshold
|
||||
) ?? false,
|
||||
disk: disk?.some((d) => diskThreshold !== -1 && typeof d?.usage_percent === "number" && d?.usage_percent > diskThreshold) ?? false,
|
||||
};
|
||||
|
||||
const alertsToSend = [];
|
||||
@@ -110,16 +91,13 @@ class NotificationUtils {
|
||||
monitor[`${type}AlertThreshold`] = monitor.alertThreshold;
|
||||
|
||||
const formatAlert = {
|
||||
cpu: () =>
|
||||
`Your current CPU usage (${(cpuUsage * 100).toFixed(0)}%) is above your threshold (${(cpuThreshold * 100).toFixed(0)}%)`,
|
||||
cpu: () => `Your current CPU usage (${(cpuUsage * 100).toFixed(0)}%) is above your threshold (${(cpuThreshold * 100).toFixed(0)}%)`,
|
||||
memory: () =>
|
||||
`Your current memory usage (${(memoryUsage * 100).toFixed(0)}%) is above your threshold (${(memoryThreshold * 100).toFixed(0)}%)`,
|
||||
disk: () =>
|
||||
`Your current disk usage: ${disk
|
||||
.map((d, idx) => `(Disk${idx}: ${(d.usage_percent * 100).toFixed(0)}%)`)
|
||||
.join(
|
||||
", "
|
||||
)} is above your threshold (${(diskThreshold * 100).toFixed(0)}%)`,
|
||||
.join(", ")} is above your threshold (${(diskThreshold * 100).toFixed(0)}%)`,
|
||||
};
|
||||
alertsToSend.push(formatAlert[type]());
|
||||
}
|
||||
|
||||
@@ -62,14 +62,10 @@ class SettingsService {
|
||||
// Remove any old settings
|
||||
await this.AppSettings.deleteMany({ version: { $exists: false } });
|
||||
|
||||
let settings = await this.AppSettings.findOne({ singleton: true })
|
||||
.select("-__v -_id -createdAt -updatedAt -singleton")
|
||||
.lean();
|
||||
let settings = await this.AppSettings.findOne({ singleton: true }).select("-__v -_id -createdAt -updatedAt -singleton").lean();
|
||||
if (settings === null) {
|
||||
await this.AppSettings.create({});
|
||||
settings = await this.AppSettings.findOne({ singleton: true })
|
||||
.select("-__v -_id -createdAt -updatedAt -singleton")
|
||||
.lean();
|
||||
settings = await this.AppSettings.findOne({ singleton: true }).select("-__v -_id -createdAt -updatedAt -singleton").lean();
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
@@ -48,9 +48,7 @@ class StatusService {
|
||||
if (avgResponseTime === 0) {
|
||||
avgResponseTime = responseTime;
|
||||
} else {
|
||||
avgResponseTime =
|
||||
(avgResponseTime * (stats.totalChecks - 1) + responseTime) /
|
||||
stats.totalChecks;
|
||||
avgResponseTime = (avgResponseTime * (stats.totalChecks - 1) + responseTime) / stats.totalChecks;
|
||||
}
|
||||
}
|
||||
stats.avgResponseTime = avgResponseTime;
|
||||
@@ -138,9 +136,7 @@ class StatusService {
|
||||
// Monitor status changed, save prev status and update monitor
|
||||
this.logger.info({
|
||||
service: this.SERVICE_NAME,
|
||||
message: `${monitor.name} went from ${this.getStatusString(
|
||||
monitor.status
|
||||
)} to ${this.getStatusString(status)}`,
|
||||
message: `${monitor.name} went from ${this.getStatusString(monitor.status)} to ${this.getStatusString(status)}`,
|
||||
prevStatus: monitor.status,
|
||||
newStatus: status,
|
||||
});
|
||||
@@ -279,9 +275,7 @@ class StatusService {
|
||||
message: error.message,
|
||||
service: error.service || this.SERVICE_NAME,
|
||||
method: error.method || "insertCheck",
|
||||
details:
|
||||
error.details ||
|
||||
`Error inserting check for monitor: ${networkResponse?.monitorId}`,
|
||||
details: error.details || `Error inserting check for monitor: ${networkResponse?.monitorId}`,
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -211,23 +211,16 @@ class StringService {
|
||||
}
|
||||
|
||||
getWebhookUnsupportedPlatform(platform) {
|
||||
return this.translationService
|
||||
.getTranslation("webhookUnsupportedPlatform")
|
||||
.replace("{platform}", platform);
|
||||
return this.translationService.getTranslation("webhookUnsupportedPlatform").replace("{platform}", platform);
|
||||
}
|
||||
|
||||
getWebhookSendError(platform) {
|
||||
return this.translationService
|
||||
.getTranslation("webhookSendError")
|
||||
.replace("{platform}", platform);
|
||||
return this.translationService.getTranslation("webhookSendError").replace("{platform}", platform);
|
||||
}
|
||||
|
||||
getMonitorStatus(name, status, url) {
|
||||
const translationKey = status === true ? "monitorStatusUp" : "monitorStatusDown";
|
||||
return this.translationService
|
||||
.getTranslation(translationKey)
|
||||
.replace("{name}", name)
|
||||
.replace("{url}", url);
|
||||
return this.translationService.getTranslation(translationKey).replace("{name}", name).replace("{url}", url);
|
||||
}
|
||||
|
||||
// Error Messages
|
||||
@@ -378,9 +371,7 @@ class StringService {
|
||||
}
|
||||
|
||||
getDeletedCount(count) {
|
||||
return this.translationService
|
||||
.getTranslation("deletedCount")
|
||||
.replace("{count}", count);
|
||||
return this.translationService.getTranslation("deletedCount").replace("{count}", count);
|
||||
}
|
||||
|
||||
get pingSuccess() {
|
||||
@@ -424,9 +415,7 @@ class StringService {
|
||||
}
|
||||
|
||||
getDbFindMonitorById(monitorId) {
|
||||
return this.translationService
|
||||
.getTranslation("dbFindMonitorById")
|
||||
.replace("${monitorId}", monitorId);
|
||||
return this.translationService.getTranslation("dbFindMonitorById").replace("${monitorId}", monitorId);
|
||||
}
|
||||
|
||||
get dbUserExists() {
|
||||
|
||||
@@ -38,9 +38,7 @@ class TranslationService {
|
||||
return false;
|
||||
}
|
||||
|
||||
const files = fs
|
||||
.readdirSync(this.localesDir)
|
||||
.filter((file) => file.endsWith(".json"));
|
||||
const files = fs.readdirSync(this.localesDir).filter((file) => file.endsWith(".json"));
|
||||
|
||||
if (files.length === 0) {
|
||||
return false;
|
||||
|
||||
@@ -32,20 +32,15 @@
|
||||
<mj-text>
|
||||
<p>Hello {{ name }}!</p>
|
||||
<p>
|
||||
We hope you’re finding Checkmate helpful in monitoring your infrastructure.
|
||||
Your support means a lot to us, and we <b>truly appreciate</b> having you as
|
||||
part of our community.
|
||||
We hope you’re finding Checkmate helpful in monitoring your infrastructure. Your support means a lot to us, and we
|
||||
<b>truly appreciate</b> having you as part of our community.
|
||||
</p>
|
||||
<p>
|
||||
If you’re happy with Checkmate, we’d love to hear about your experience!
|
||||
Leaving a review on G2 helps others discover Checkmate and supports our
|
||||
ongoing improvements.
|
||||
If you’re happy with Checkmate, we’d love to hear about your experience! Leaving a review on G2 helps others discover Checkmate and
|
||||
supports our ongoing improvements.
|
||||
</p>
|
||||
G2 Link: TBD
|
||||
<p>
|
||||
Thank you for taking the time to share your thoughts - we greatly appreciate
|
||||
it!
|
||||
</p>
|
||||
<p>Thank you for taking the time to share your thoughts - we greatly appreciate it!</p>
|
||||
Checkmate Team
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
|
||||
@@ -1,56 +1,42 @@
|
||||
<!-- name, email, url -->
|
||||
|
||||
<mjml>
|
||||
<mj-head>
|
||||
<mj-font
|
||||
name="Roboto"
|
||||
href="https://fonts.googleapis.com/css?family=Roboto:300,500"
|
||||
></mj-font>
|
||||
<mj-attributes>
|
||||
<mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all>
|
||||
<mj-text
|
||||
font-weight="300"
|
||||
font-size="16px"
|
||||
color="#616161"
|
||||
line-height="24px"
|
||||
></mj-text>
|
||||
<mj-section padding="0px"></mj-section>
|
||||
</mj-attributes>
|
||||
</mj-head>
|
||||
<mj-body>
|
||||
<mj-section padding="20px 0">
|
||||
<mj-column width="100%">
|
||||
<mj-text
|
||||
align="left"
|
||||
font-size="10px"
|
||||
>
|
||||
Message from Checkmate Service
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
</mj-section>
|
||||
<mj-section>
|
||||
<mj-column width="100%">
|
||||
<mj-text>
|
||||
<p>Hello {{ name }}!</p>
|
||||
<p>
|
||||
You are receiving this email because a password reset request has been made
|
||||
for {{ email }}. Please use the link below on the site to reset your password.
|
||||
</p>
|
||||
<a href="{{url}}">Reset Password</a>
|
||||
<p>If you didn't request this, please ignore this email.</p>
|
||||
<mj-head>
|
||||
<mj-font name="Roboto" href="https://fonts.googleapis.com/css?family=Roboto:300,500"></mj-font>
|
||||
<mj-attributes>
|
||||
<mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all>
|
||||
<mj-text font-weight="300" font-size="16px" color="#616161" line-height="24px"></mj-text>
|
||||
<mj-section padding="0px"></mj-section>
|
||||
</mj-attributes>
|
||||
</mj-head>
|
||||
<mj-body>
|
||||
<mj-section padding="20px 0">
|
||||
<mj-column width="100%">
|
||||
<mj-text align="left" font-size="10px">
|
||||
Message from Checkmate Service
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
</mj-section>
|
||||
<mj-section>
|
||||
<mj-column width="100%">
|
||||
<mj-text>
|
||||
<p>Hello {{ name }}!</p>
|
||||
<p>
|
||||
You are receiving this email because a password reset request has been made for {{ email }}. Please use the link below on the site to
|
||||
reset your password.
|
||||
</p>
|
||||
<a href="{{url}}">Reset Password</a>
|
||||
<p>If you didn't request this, please ignore this email.</p>
|
||||
|
||||
<p>Thank you.</p>
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
<mj-column width="100%">
|
||||
<mj-divider
|
||||
border-width="1px"
|
||||
border-color="#E0E0E0"
|
||||
></mj-divider>
|
||||
<mj-text font-size="12px">
|
||||
<p>This email was sent by Checkmate.</p>
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
</mj-section>
|
||||
</mj-body>
|
||||
</mjml>
|
||||
<p>Thank you.</p>
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
<mj-column width="100%">
|
||||
<mj-divider border-width="1px" border-color="#E0E0E0"></mj-divider>
|
||||
<mj-text font-size="12px">
|
||||
<p>This email was sent by Checkmate.</p>
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
</mj-section>
|
||||
</mj-body>
|
||||
</mjml>
|
||||
@@ -1,71 +1,42 @@
|
||||
<mjml>
|
||||
<mj-head>
|
||||
<mj-font
|
||||
name="Roboto"
|
||||
href="https://fonts.googleapis.com/css?family=Roboto:300,500"
|
||||
></mj-font>
|
||||
<mj-attributes>
|
||||
<mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all>
|
||||
<mj-text
|
||||
font-weight="300"
|
||||
font-size="16px"
|
||||
color="#616161"
|
||||
line-height="24px"
|
||||
></mj-text>
|
||||
<mj-section padding="0px"></mj-section>
|
||||
</mj-attributes>
|
||||
</mj-head>
|
||||
<mj-body>
|
||||
<mj-section padding="20px 0">
|
||||
<mj-column width="100%">
|
||||
<mj-text
|
||||
align="left"
|
||||
font-size="10px"
|
||||
>
|
||||
Message from Checkmate Service
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
<mj-column
|
||||
width="45%"
|
||||
padding-top="20px"
|
||||
>
|
||||
<mj-text
|
||||
align="center"
|
||||
font-weight="500"
|
||||
padding="0px"
|
||||
font-size="18px"
|
||||
color="red"
|
||||
>
|
||||
{{ monitor }} is down
|
||||
</mj-text>
|
||||
<mj-divider
|
||||
border-width="2px"
|
||||
border-color="#616161"
|
||||
></mj-divider>
|
||||
</mj-column>
|
||||
</mj-section>
|
||||
<mj-section>
|
||||
<mj-column width="100%">
|
||||
<mj-text>
|
||||
<p>Hello {{ name }}!</p>
|
||||
<p>
|
||||
We detected an incident on one of your monitors. Your service is currently
|
||||
down. We'll send a message to you once it is up again.
|
||||
</p>
|
||||
<p><b>Monitor name:</b> {{ monitor }}</p>
|
||||
<p><b>URL:</b> {{ url }}</p>
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
<mj-column width="100%">
|
||||
<mj-divider
|
||||
border-width="1px"
|
||||
border-color="#E0E0E0"
|
||||
></mj-divider>
|
||||
<mj-button background-color="#1570EF"> View incident details </mj-button>
|
||||
<mj-text font-size="12px">
|
||||
<p>This email was sent by Checkmate.</p>
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
</mj-section>
|
||||
</mj-body>
|
||||
</mjml>
|
||||
<mj-head>
|
||||
<mj-font name="Roboto" href="https://fonts.googleapis.com/css?family=Roboto:300,500"></mj-font>
|
||||
<mj-attributes>
|
||||
<mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all>
|
||||
<mj-text font-weight="300" font-size="16px" color="#616161" line-height="24px"></mj-text>
|
||||
<mj-section padding="0px"></mj-section>
|
||||
</mj-attributes>
|
||||
</mj-head>
|
||||
<mj-body>
|
||||
<mj-section padding="20px 0">
|
||||
<mj-column width="100%">
|
||||
<mj-text align="left" font-size="10px">
|
||||
Message from Checkmate Service
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
<mj-column width="45%" padding-top="20px">
|
||||
<mj-text align="center" font-weight="500" padding="0px" font-size="18px" color="red">
|
||||
{{ monitor }} is down
|
||||
</mj-text>
|
||||
<mj-divider border-width="2px" border-color="#616161"></mj-divider>
|
||||
</mj-column>
|
||||
</mj-section>
|
||||
<mj-section>
|
||||
<mj-column width="100%">
|
||||
<mj-text>
|
||||
<p>Hello {{ name }}!</p>
|
||||
<p>We detected an incident on one of your monitors. Your service is currently down. We'll send a message to you once it is up again.</p>
|
||||
<p><b>Monitor name:</b> {{ monitor }}</p>
|
||||
<p><b>URL:</b> {{ url }}</p>
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
<mj-column width="100%">
|
||||
<mj-divider border-width="1px" border-color="#E0E0E0"></mj-divider>
|
||||
<mj-button background-color="#1570EF"> View incident details </mj-button>
|
||||
<mj-text font-size="12px">
|
||||
<p>This email was sent by Checkmate.</p>
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
</mj-section>
|
||||
</mj-body>
|
||||
</mjml>
|
||||
@@ -1,57 +1,37 @@
|
||||
<!-- name -->
|
||||
<mjml>
|
||||
<mj-head>
|
||||
<mj-font
|
||||
name="Roboto"
|
||||
href="https://fonts.googleapis.com/css?family=Roboto:300,500"
|
||||
></mj-font>
|
||||
<mj-attributes>
|
||||
<mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all>
|
||||
<mj-text
|
||||
font-weight="300"
|
||||
font-size="16px"
|
||||
color="#616161"
|
||||
line-height="24px"
|
||||
></mj-text>
|
||||
<mj-section padding="0px"></mj-section>
|
||||
</mj-attributes>
|
||||
</mj-head>
|
||||
<mj-body>
|
||||
<mj-section padding="20px 0">
|
||||
<mj-column width="100%">
|
||||
<mj-text
|
||||
align="left"
|
||||
font-size="10px"
|
||||
>
|
||||
Message from Checkmate Service
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
</mj-section>
|
||||
<mj-section>
|
||||
<mj-column width="100%">
|
||||
<mj-text>
|
||||
<p>Hello {{ name }}!</p>
|
||||
<p>
|
||||
Thank you for trying out Checkmate! We developed it with great care to meet
|
||||
our own needs, and we're excited to share it with you.
|
||||
</p>
|
||||
<p>
|
||||
Checkmate is an automated way of checking whether a service such as a website
|
||||
or an application is available or not.
|
||||
</p>
|
||||
<p>We hope you find our service as valuable as we do.</p>
|
||||
<p>Thank you.</p>
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
<mj-column width="100%">
|
||||
<mj-divider
|
||||
border-width="1px"
|
||||
border-color="#E0E0E0"
|
||||
></mj-divider>
|
||||
<mj-text font-size="12px">
|
||||
<p>This email was sent by Checkmate.</p>
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
</mj-section>
|
||||
</mj-body>
|
||||
</mjml>
|
||||
<mj-head>
|
||||
<mj-font name="Roboto" href="https://fonts.googleapis.com/css?family=Roboto:300,500"></mj-font>
|
||||
<mj-attributes>
|
||||
<mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all>
|
||||
<mj-text font-weight="300" font-size="16px" color="#616161" line-height="24px"></mj-text>
|
||||
<mj-section padding="0px"></mj-section>
|
||||
</mj-attributes>
|
||||
</mj-head>
|
||||
<mj-body>
|
||||
<mj-section padding="20px 0">
|
||||
<mj-column width="100%">
|
||||
<mj-text align="left" font-size="10px">
|
||||
Message from Checkmate Service
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
</mj-section>
|
||||
<mj-section>
|
||||
<mj-column width="100%">
|
||||
<mj-text>
|
||||
<p>Hello {{ name }}!</p>
|
||||
<p>Thank you for trying out Checkmate! We developed it with great care to meet our own needs, and we're excited to share it with you.</p>
|
||||
<p>Checkmate is an automated way of checking whether a service such as a website or an application is available or not.</p>
|
||||
<p>We hope you find our service as valuable as we do.</p>
|
||||
<p>Thank you.</p>
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
<mj-column width="100%">
|
||||
<mj-divider border-width="1px" border-color="#E0E0E0"></mj-divider>
|
||||
<mj-text font-size="12px">
|
||||
<p>This email was sent by Checkmate.</p>
|
||||
</mj-text>
|
||||
</mj-column>
|
||||
</mj-section>
|
||||
</mj-body>
|
||||
</mjml>
|
||||
@@ -28,9 +28,7 @@ describe("Auth Controller - issueToken", function () {
|
||||
stub = sinon.stub(jwt, "sign").throws(error);
|
||||
const payload = { id: "123" };
|
||||
const appSettings = { jwtSecret: "my_secret" };
|
||||
expect(() => issueToken(payload, tokenType.ACCESS_TOKEN, appSettings)).to.throw(
|
||||
error
|
||||
);
|
||||
expect(() => issueToken(payload, tokenType.ACCESS_TOKEN, appSettings)).to.throw(error);
|
||||
});
|
||||
|
||||
it("should return a token if jwt.sign is successful and appSettings.jwtTTL is not defined", function () {
|
||||
@@ -163,9 +161,7 @@ describe("Auth Controller - registerUser", function () {
|
||||
req.db.checkSuperadmin.resolves(false);
|
||||
req.db.updateAppSettings.resolves();
|
||||
req.db.insertUser.resolves({ _id: "123" });
|
||||
req.settingsService.getSettings.rejects(
|
||||
new Error("settingsService.getSettings error")
|
||||
);
|
||||
req.settingsService.getSettings.rejects(new Error("settingsService.getSettings error"));
|
||||
await registerUser(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("settingsService.getSettings error");
|
||||
@@ -304,9 +300,7 @@ describe("Auth Controller - loginUser", function () {
|
||||
user.comparePassword.resolves(false);
|
||||
await loginUser(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal(
|
||||
errorMessages.AUTH_INCORRECT_PASSWORD
|
||||
);
|
||||
expect(next.firstCall.args[0].message).to.equal(errorMessages.AUTH_INCORRECT_PASSWORD);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -370,9 +364,7 @@ describe("Auth Controller - refreshAuthToken", function () {
|
||||
});
|
||||
|
||||
it("should reject if settingsService.getSettings fails", async function () {
|
||||
req.settingsService.getSettings.rejects(
|
||||
new Error("settingsService.getSettings error")
|
||||
);
|
||||
req.settingsService.getSettings.rejects(new Error("settingsService.getSettings error"));
|
||||
await refreshAuthToken(req, res, next);
|
||||
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
@@ -475,9 +467,7 @@ describe("Auth Controller - editUser", function () {
|
||||
await editUser(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(401);
|
||||
expect(next.firstCall.args[0].message).to.equal(
|
||||
errorMessages.AUTH_INCORRECT_PASSWORD
|
||||
);
|
||||
expect(next.firstCall.args[0].message).to.equal(errorMessages.AUTH_INCORRECT_PASSWORD);
|
||||
});
|
||||
|
||||
it("should edit a user if it receives a proper request", async function () {
|
||||
@@ -863,8 +853,7 @@ describe("Auth Controller - deleteUser", function () {
|
||||
).to.be.true;
|
||||
expect(req.jobQueue.deleteJob.calledOnceWith(monitors[0])).to.be.true;
|
||||
expect(req.db.deleteChecks.calledOnceWith("monitor_id")).to.be.true;
|
||||
expect(req.db.deletePageSpeedChecksByMonitorId.calledOnceWith("monitor_id")).to.be
|
||||
.true;
|
||||
expect(req.db.deletePageSpeedChecksByMonitorId.calledOnceWith("monitor_id")).to.be.true;
|
||||
expect(req.db.deleteNotificationsByMonitorId.calledOnceWith("monitor_id")).to.be.true;
|
||||
expect(req.db.deleteTeam.calledOnceWith("team_id")).to.be.true;
|
||||
expect(req.db.deleteAllOtherUsers.calledOnce).to.be.true;
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
import {
|
||||
createCheck,
|
||||
getChecks,
|
||||
getTeamChecks,
|
||||
deleteChecks,
|
||||
deleteChecksByTeamId,
|
||||
updateChecksTTL,
|
||||
} from "../../controllers/checkController.js";
|
||||
import { createCheck, getChecks, getTeamChecks, deleteChecks, deleteChecksByTeamId, updateChecksTTL } from "../../controllers/checkController.js";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { errorMessages, successMessages } from "../../utils/messages.js";
|
||||
import sinon from "sinon";
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import sinon from "sinon";
|
||||
|
||||
import {
|
||||
handleValidationError,
|
||||
handleError,
|
||||
fetchMonitorCertificate,
|
||||
} from "../../controllers/controllerUtils.js";
|
||||
import { handleValidationError, handleError, fetchMonitorCertificate } from "../../controllers/controllerUtils.js";
|
||||
import { expect } from "chai";
|
||||
import sslChecker from "ssl-checker";
|
||||
import { afterEach } from "node:test";
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import {
|
||||
issueInvitation,
|
||||
inviteVerifyController,
|
||||
} from "../../controllers/inviteController.js";
|
||||
import { issueInvitation, inviteVerifyController } from "../../controllers/inviteController.js";
|
||||
import jwt from "jsonwebtoken";
|
||||
import sinon from "sinon";
|
||||
import joi from "joi";
|
||||
|
||||
@@ -623,9 +623,7 @@ describe("Monitor Controller - deleteMonitor", function () {
|
||||
req.jobQueue.deleteJob.rejects(error);
|
||||
await deleteMonitor(req, res, next);
|
||||
expect(logger.error.calledOnce).to.be.true;
|
||||
expect(logger.error.firstCall.args[0].message).to.equal(
|
||||
`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`
|
||||
);
|
||||
expect(logger.error.firstCall.args[0].message).to.equal(`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`);
|
||||
});
|
||||
|
||||
it("should log an error if deleteChecks throws an error", async function () {
|
||||
@@ -635,9 +633,7 @@ describe("Monitor Controller - deleteMonitor", function () {
|
||||
req.db.deleteChecks.rejects(error);
|
||||
await deleteMonitor(req, res, next);
|
||||
expect(logger.error.calledOnce).to.be.true;
|
||||
expect(logger.error.firstCall.args[0].message).to.equal(
|
||||
`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`
|
||||
);
|
||||
expect(logger.error.firstCall.args[0].message).to.equal(`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`);
|
||||
});
|
||||
|
||||
it("should log an error if deletePageSpeedChecksByMonitorId throws an error", async function () {
|
||||
@@ -647,9 +643,7 @@ describe("Monitor Controller - deleteMonitor", function () {
|
||||
req.db.deletePageSpeedChecksByMonitorId.rejects(error);
|
||||
await deleteMonitor(req, res, next);
|
||||
expect(logger.error.calledOnce).to.be.true;
|
||||
expect(logger.error.firstCall.args[0].message).to.equal(
|
||||
`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`
|
||||
);
|
||||
expect(logger.error.firstCall.args[0].message).to.equal(`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`);
|
||||
});
|
||||
|
||||
it("should log an error if deleteNotificationsByMonitorId throws an error", async function () {
|
||||
@@ -659,9 +653,7 @@ describe("Monitor Controller - deleteMonitor", function () {
|
||||
req.db.deleteNotificationsByMonitorId.rejects(error);
|
||||
await deleteMonitor(req, res, next);
|
||||
expect(logger.error.calledOnce).to.be.true;
|
||||
expect(logger.error.firstCall.args[0].message).to.equal(
|
||||
`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`
|
||||
);
|
||||
expect(logger.error.firstCall.args[0].message).to.equal(`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`);
|
||||
});
|
||||
|
||||
it("should return success message if all operations succeed", async function () {
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import { afterEach } from "node:test";
|
||||
import {
|
||||
getMetrics,
|
||||
getJobs,
|
||||
addJob,
|
||||
obliterateQueue,
|
||||
} from "../../controllers/queueController.js";
|
||||
import { getMetrics, getJobs, addJob, obliterateQueue } from "../../controllers/queueController.js";
|
||||
import { successMessages } from "../../utils/messages.js";
|
||||
import sinon from "sinon";
|
||||
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { afterEach } from "node:test";
|
||||
import {
|
||||
getAppSettings,
|
||||
updateAppSettings,
|
||||
} from "../../controllers/settingsController.js";
|
||||
import { getAppSettings, updateAppSettings } from "../../controllers/settingsController.js";
|
||||
|
||||
import { successMessages } from "../../utils/messages.js";
|
||||
import sinon from "sinon";
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import sinon from "sinon";
|
||||
import {
|
||||
createStatusPage,
|
||||
getStatusPageByUrl,
|
||||
} from "../../controllers/statusPageController.js";
|
||||
import { createStatusPage, getStatusPageByUrl } from "../../controllers/statusPageController.js";
|
||||
|
||||
describe("statusPageController", function () {
|
||||
let req, res, next;
|
||||
|
||||
@@ -216,11 +216,7 @@ describe("checkModule", function () {
|
||||
const result = await getChecksCount(req);
|
||||
|
||||
expect(result).to.equal(4);
|
||||
expect(checkCountDocumentStub.firstCall.args[0]).to.have.all.keys(
|
||||
"monitorId",
|
||||
"createdAt",
|
||||
"status"
|
||||
);
|
||||
expect(checkCountDocumentStub.firstCall.args[0]).to.have.all.keys("monitorId", "createdAt", "status");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -52,10 +52,7 @@ const mockMonitor = {
|
||||
};
|
||||
|
||||
describe("HardwareCheckModule", function () {
|
||||
let hardwareCheckSaveStub,
|
||||
hardwareCheckCountDocumentsStub,
|
||||
monitorFindByIdStub,
|
||||
loggerStub;
|
||||
let hardwareCheckSaveStub, hardwareCheckCountDocumentsStub, monitorFindByIdStub, loggerStub;
|
||||
|
||||
beforeEach(function () {
|
||||
loggerStub = sinon.stub(logger, "error");
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import sinon from "sinon";
|
||||
import InviteToken from "../../db/models/InviteToken.js";
|
||||
import {
|
||||
requestInviteToken,
|
||||
getInviteToken,
|
||||
getInviteTokenAndDelete,
|
||||
} from "../../db/mongo/modules/inviteModule.js";
|
||||
import { requestInviteToken, getInviteToken, getInviteTokenAndDelete } from "../../db/mongo/modules/inviteModule.js";
|
||||
import { errorMessages } from "../../utils/messages.js";
|
||||
|
||||
describe("Invite Module", function () {
|
||||
@@ -15,10 +11,7 @@ describe("Invite Module", function () {
|
||||
token: "123",
|
||||
};
|
||||
const mockInviteToken = { _id: 123, time: 123 };
|
||||
let inviteTokenDeleteManyStub,
|
||||
inviteTokenSaveStub,
|
||||
inviteTokenFindOneStub,
|
||||
inviteTokenFindOneAndDeleteStub;
|
||||
let inviteTokenDeleteManyStub, inviteTokenSaveStub, inviteTokenFindOneStub, inviteTokenFindOneAndDeleteStub;
|
||||
|
||||
beforeEach(function () {
|
||||
inviteTokenDeleteManyStub = sinon.stub(InviteToken, "deleteMany");
|
||||
|
||||
@@ -40,15 +40,9 @@ describe("MaintenanceWindow Module", function () {
|
||||
}),
|
||||
}),
|
||||
});
|
||||
maintenanceWindowFindByIdAndDeleteStub = sinon.stub(
|
||||
MaintenanceWindow,
|
||||
"findByIdAndDelete"
|
||||
);
|
||||
maintenanceWindowFindByIdAndDeleteStub = sinon.stub(MaintenanceWindow, "findByIdAndDelete");
|
||||
maintenanceWindowDeleteManyStub = sinon.stub(MaintenanceWindow, "deleteMany");
|
||||
maintenanceWindowFindByIdAndUpdateStub = sinon.stub(
|
||||
MaintenanceWindow,
|
||||
"findByIdAndUpdate"
|
||||
);
|
||||
maintenanceWindowFindByIdAndUpdateStub = sinon.stub(MaintenanceWindow, "findByIdAndUpdate");
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
@@ -110,10 +104,7 @@ describe("MaintenanceWindow Module", function () {
|
||||
|
||||
it("should return a list of maintenance windows and count", async function () {
|
||||
maintenanceWindowCountDocumentsStub.resolves(1);
|
||||
const result = await getMaintenanceWindowsByTeamId(
|
||||
mockMaintenanceWindow.teamId,
|
||||
query
|
||||
);
|
||||
const result = await getMaintenanceWindowsByTeamId(mockMaintenanceWindow.teamId, query);
|
||||
expect(result).to.deep.equal({
|
||||
maintenanceWindows: mockMaintenanceWindows,
|
||||
maintenanceWindowCount: 1,
|
||||
@@ -123,10 +114,7 @@ describe("MaintenanceWindow Module", function () {
|
||||
it("should return a list of maintenance windows and count with empty query", async function () {
|
||||
query = undefined;
|
||||
maintenanceWindowCountDocumentsStub.resolves(1);
|
||||
const result = await getMaintenanceWindowsByTeamId(
|
||||
mockMaintenanceWindow.teamId,
|
||||
query
|
||||
);
|
||||
const result = await getMaintenanceWindowsByTeamId(mockMaintenanceWindow.teamId, query);
|
||||
expect(result).to.deep.equal({
|
||||
maintenanceWindows: mockMaintenanceWindows,
|
||||
maintenanceWindowCount: 1,
|
||||
@@ -137,10 +125,7 @@ describe("MaintenanceWindow Module", function () {
|
||||
query.page = undefined;
|
||||
query.rowsPerPage = undefined;
|
||||
maintenanceWindowCountDocumentsStub.resolves(1);
|
||||
const result = await getMaintenanceWindowsByTeamId(
|
||||
mockMaintenanceWindow.teamId,
|
||||
query
|
||||
);
|
||||
const result = await getMaintenanceWindowsByTeamId(mockMaintenanceWindow.teamId, query);
|
||||
expect(result).to.deep.equal({
|
||||
maintenanceWindows: mockMaintenanceWindows,
|
||||
maintenanceWindowCount: 1,
|
||||
@@ -150,10 +135,7 @@ describe("MaintenanceWindow Module", function () {
|
||||
it("should return a list of maintenance windows and count with field and desc order", async function () {
|
||||
query.order = "desc";
|
||||
maintenanceWindowCountDocumentsStub.resolves(1);
|
||||
const result = await getMaintenanceWindowsByTeamId(
|
||||
mockMaintenanceWindow.teamId,
|
||||
query
|
||||
);
|
||||
const result = await getMaintenanceWindowsByTeamId(mockMaintenanceWindow.teamId, query);
|
||||
expect(result).to.deep.equal({
|
||||
maintenanceWindows: mockMaintenanceWindows,
|
||||
maintenanceWindowCount: 1,
|
||||
@@ -163,10 +145,7 @@ describe("MaintenanceWindow Module", function () {
|
||||
it("should return a list of maintenance windows and count no field", async function () {
|
||||
query.field = undefined;
|
||||
maintenanceWindowCountDocumentsStub.resolves(1);
|
||||
const result = await getMaintenanceWindowsByTeamId(
|
||||
mockMaintenanceWindow.teamId,
|
||||
query
|
||||
);
|
||||
const result = await getMaintenanceWindowsByTeamId(mockMaintenanceWindow.teamId, query);
|
||||
expect(result).to.deep.equal({
|
||||
maintenanceWindows: mockMaintenanceWindows,
|
||||
maintenanceWindowCount: 1,
|
||||
@@ -187,9 +166,7 @@ describe("MaintenanceWindow Module", function () {
|
||||
describe("getMaintenanceWindowsByMonitorId", function () {
|
||||
it("should return a list of maintenance windows", async function () {
|
||||
maintenanceWindowFindStub.resolves(mockMaintenanceWindows);
|
||||
const result = await getMaintenanceWindowsByMonitorId(
|
||||
mockMaintenanceWindow.monitorId
|
||||
);
|
||||
const result = await getMaintenanceWindowsByMonitorId(mockMaintenanceWindow.monitorId);
|
||||
expect(result).to.deep.equal(mockMaintenanceWindows);
|
||||
});
|
||||
|
||||
@@ -225,9 +202,7 @@ describe("MaintenanceWindow Module", function () {
|
||||
describe("deleteMaintenanceWindowByMonitorId", function () {
|
||||
it("should return the number of documents deleted", async function () {
|
||||
maintenanceWindowDeleteManyStub.resolves({ deletedCount: 1 });
|
||||
const result = await deleteMaintenanceWindowByMonitorId(
|
||||
mockMaintenanceWindow.monitorId
|
||||
);
|
||||
const result = await deleteMaintenanceWindowByMonitorId(mockMaintenanceWindow.monitorId);
|
||||
expect(result).to.deep.equal({ deletedCount: 1 });
|
||||
});
|
||||
|
||||
@@ -263,10 +238,7 @@ describe("MaintenanceWindow Module", function () {
|
||||
describe("editMaintenanceWindowById", function () {
|
||||
it("should return the updated maintenance window", async function () {
|
||||
maintenanceWindowFindByIdAndUpdateStub.resolves(mockMaintenanceWindow);
|
||||
const result = await editMaintenanceWindowById(
|
||||
mockMaintenanceWindow.id,
|
||||
mockMaintenanceWindow
|
||||
);
|
||||
const result = await editMaintenanceWindowById(mockMaintenanceWindow.id, mockMaintenanceWindow);
|
||||
expect(result).to.deep.equal(mockMaintenanceWindow);
|
||||
});
|
||||
|
||||
|
||||
@@ -120,12 +120,7 @@ describe("monitorModule", function () {
|
||||
},
|
||||
];
|
||||
|
||||
const mockChecks = [
|
||||
{ status: true },
|
||||
{ status: true },
|
||||
{ status: false },
|
||||
{ status: true },
|
||||
];
|
||||
const mockChecks = [{ status: true }, { status: true }, { status: false }, { status: true }];
|
||||
|
||||
monitorFindStub.resolves(mockMonitors);
|
||||
checkFindStub.resolves(mockChecks);
|
||||
@@ -166,12 +161,7 @@ describe("monitorModule", function () {
|
||||
},
|
||||
];
|
||||
|
||||
const mockChecks = [
|
||||
{ status: true },
|
||||
{ status: true },
|
||||
{ status: false },
|
||||
{ status: true },
|
||||
];
|
||||
const mockChecks = [{ status: true }, { status: true }, { status: false }, { status: true }];
|
||||
|
||||
monitorFindStub.resolves(mockMonitors);
|
||||
pageSpeedCheckFindStub.resolves(mockChecks);
|
||||
@@ -212,12 +202,7 @@ describe("monitorModule", function () {
|
||||
},
|
||||
];
|
||||
|
||||
const mockChecks = [
|
||||
{ status: true },
|
||||
{ status: true },
|
||||
{ status: false },
|
||||
{ status: true },
|
||||
];
|
||||
const mockChecks = [{ status: true }, { status: true }, { status: false }, { status: true }];
|
||||
|
||||
monitorFindStub.resolves(mockMonitors);
|
||||
hardwareCheckFindStub.resolves(mockChecks);
|
||||
@@ -400,10 +385,7 @@ describe("monitorModule", function () {
|
||||
});
|
||||
|
||||
it("should handle missing responseTime in checks", function () {
|
||||
const checks = [
|
||||
{ createdAt: "2024-01-01T11:30:00Z" },
|
||||
{ responseTime: 200, createdAt: "2024-01-01T11:00:00Z" },
|
||||
];
|
||||
const checks = [{ createdAt: "2024-01-01T11:30:00Z" }, { responseTime: 200, createdAt: "2024-01-01T11:00:00Z" }];
|
||||
|
||||
expect(getLatestResponseTime(checks)).to.equal(0);
|
||||
});
|
||||
@@ -441,10 +423,7 @@ describe("monitorModule", function () {
|
||||
});
|
||||
|
||||
it("should return 0 when no checks have responseTime", function () {
|
||||
const checks = [
|
||||
{ createdAt: "2024-01-01T11:30:00Z" },
|
||||
{ createdAt: "2024-01-01T11:00:00Z" },
|
||||
];
|
||||
const checks = [{ createdAt: "2024-01-01T11:30:00Z" }, { createdAt: "2024-01-01T11:00:00Z" }];
|
||||
|
||||
expect(getAverageResponseTime(checks)).to.equal(0);
|
||||
});
|
||||
@@ -470,12 +449,7 @@ describe("monitorModule", function () {
|
||||
});
|
||||
|
||||
it("should calculate correct percentage for mixed status checks", function () {
|
||||
const checks = [
|
||||
{ status: true },
|
||||
{ status: false },
|
||||
{ status: true },
|
||||
{ status: true },
|
||||
];
|
||||
const checks = [{ status: true }, { status: false }, { status: true }, { status: true }];
|
||||
// 3 up out of 4 total = 75%
|
||||
expect(getUptimePercentage(checks)).to.equal(75);
|
||||
});
|
||||
@@ -507,23 +481,12 @@ describe("monitorModule", function () {
|
||||
});
|
||||
|
||||
it("should count correct number of incidents for mixed status checks", function () {
|
||||
const checks = [
|
||||
{ status: true },
|
||||
{ status: false },
|
||||
{ status: true },
|
||||
{ status: false },
|
||||
{ status: true },
|
||||
];
|
||||
const checks = [{ status: true }, { status: false }, { status: true }, { status: false }, { status: true }];
|
||||
expect(getIncidents(checks)).to.equal(2);
|
||||
});
|
||||
|
||||
it("should handle undefined status values", function () {
|
||||
const checks = [
|
||||
{ status: true },
|
||||
{ status: undefined },
|
||||
{ status: false },
|
||||
{ status: false },
|
||||
];
|
||||
const checks = [{ status: true }, { status: undefined }, { status: false }, { status: false }];
|
||||
// Only counts explicit false values
|
||||
expect(getIncidents(checks)).to.equal(2);
|
||||
});
|
||||
@@ -628,12 +591,8 @@ describe("monitorModule", function () {
|
||||
);
|
||||
|
||||
// Assert
|
||||
expect(result.checksAll[0].createdAt).to.be.greaterThan(
|
||||
result.checksAll[1].createdAt
|
||||
);
|
||||
expect(result.checksForDateRange[0].createdAt).to.be.greaterThan(
|
||||
result.checksForDateRange[1].createdAt
|
||||
);
|
||||
expect(result.checksAll[0].createdAt).to.be.greaterThan(result.checksAll[1].createdAt);
|
||||
expect(result.checksForDateRange[0].createdAt).to.be.greaterThan(result.checksForDateRange[1].createdAt);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -753,10 +712,7 @@ describe("monitorModule", function () {
|
||||
});
|
||||
|
||||
it("should handle checks in same time group", function () {
|
||||
const checksInSameHour = [
|
||||
{ createdAt: "2024-01-15T10:15:00Z" },
|
||||
{ createdAt: "2024-01-15T10:45:00Z" },
|
||||
];
|
||||
const checksInSameHour = [{ createdAt: "2024-01-15T10:15:00Z" }, { createdAt: "2024-01-15T10:45:00Z" }];
|
||||
|
||||
const result = groupChecksByTime(checksInSameHour, "day");
|
||||
|
||||
@@ -816,11 +772,7 @@ describe("monitorModule", function () {
|
||||
it("should handle missing responseTime values", function () {
|
||||
const mockGroup = {
|
||||
time: "2024-01-15",
|
||||
checks: [
|
||||
{ status: true },
|
||||
{ status: false, responseTime: 200 },
|
||||
{ status: true, responseTime: undefined },
|
||||
],
|
||||
checks: [{ status: true }, { status: false, responseTime: 200 }, { status: true, responseTime: undefined }],
|
||||
};
|
||||
|
||||
const result = calculateGroupStats(mockGroup, uptimePercentageStub);
|
||||
@@ -1413,10 +1365,7 @@ describe("monitorModule", function () {
|
||||
|
||||
expect(Monitor.find.firstCall.args[0]).to.deep.equal({
|
||||
teamId: "team123",
|
||||
$or: [
|
||||
{ name: { $regex: "search", $options: "i" } },
|
||||
{ url: { $regex: "search", $options: "i" } },
|
||||
],
|
||||
$or: [{ name: { $regex: "search", $options: "i" } }, { url: { $regex: "search", $options: "i" } }],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1816,14 +1765,9 @@ describe("monitorModule", function () {
|
||||
|
||||
// Assert
|
||||
expect(result).to.deep.equal(mockUpdatedMonitor);
|
||||
sinon.assert.calledWith(
|
||||
monitorFindByIdAndUpdateStub,
|
||||
candidateId,
|
||||
expectedUpdateData,
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
);
|
||||
sinon.assert.calledWith(monitorFindByIdAndUpdateStub, candidateId, expectedUpdateData, {
|
||||
new: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("should return null when monitor not found", async function () {
|
||||
@@ -1840,12 +1784,7 @@ describe("monitorModule", function () {
|
||||
|
||||
// Assert
|
||||
expect(result).to.be.null;
|
||||
sinon.assert.calledWith(
|
||||
monitorFindByIdAndUpdateStub,
|
||||
candidateId,
|
||||
{ name: "Updated Monitor", notifications: undefined },
|
||||
{ new: true }
|
||||
);
|
||||
sinon.assert.calledWith(monitorFindByIdAndUpdateStub, candidateId, { name: "Updated Monitor", notifications: undefined }, { new: true });
|
||||
});
|
||||
|
||||
it("should remove notifications from update data", async function () {
|
||||
@@ -1870,14 +1809,9 @@ describe("monitorModule", function () {
|
||||
await editMonitor(candidateId, candidateMonitor);
|
||||
|
||||
// Assert
|
||||
sinon.assert.calledWith(
|
||||
monitorFindByIdAndUpdateStub,
|
||||
candidateId,
|
||||
expectedUpdateData,
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
);
|
||||
sinon.assert.calledWith(monitorFindByIdAndUpdateStub, candidateId, expectedUpdateData, {
|
||||
new: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle database errors", async function () {
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import sinon from "sinon";
|
||||
import Notification from "../../db/models/Notification.js";
|
||||
import {
|
||||
createNotification,
|
||||
getNotificationsByMonitorId,
|
||||
deleteNotificationsByMonitorId,
|
||||
} from "../../db/mongo/modules/notificationModule.js";
|
||||
import { createNotification, getNotificationsByMonitorId, deleteNotificationsByMonitorId } from "../../db/mongo/modules/notificationModule.js";
|
||||
|
||||
describe("notificationModule", function () {
|
||||
const mockNotification = {
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import sinon from "sinon";
|
||||
import PageSpeedCheck from "../../db/models/PageSpeedCheck.js";
|
||||
import {
|
||||
createPageSpeedCheck,
|
||||
deletePageSpeedChecksByMonitorId,
|
||||
} from "../../db/mongo/modules/pageSpeedCheckModule.js";
|
||||
import { createPageSpeedCheck, deletePageSpeedChecksByMonitorId } from "../../db/mongo/modules/pageSpeedCheckModule.js";
|
||||
|
||||
const mockPageSpeedCheck = {
|
||||
monitorId: "monitorId",
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import sinon from "sinon";
|
||||
import RecoveryToken from "../../db/models/RecoveryToken.js";
|
||||
import User from "../../db/models/User.js";
|
||||
import {
|
||||
requestRecoveryToken,
|
||||
validateRecoveryToken,
|
||||
resetPassword,
|
||||
} from "../../db/mongo/modules/recoveryModule.js";
|
||||
import { requestRecoveryToken, validateRecoveryToken, resetPassword } from "../../db/mongo/modules/recoveryModule.js";
|
||||
import { errorMessages } from "../../utils/messages.js";
|
||||
|
||||
const mockRecoveryToken = {
|
||||
@@ -44,12 +40,7 @@ const createQueryChain = (finalResult, comparePasswordResult = false) => ({
|
||||
});
|
||||
|
||||
describe("recoveryModule", function () {
|
||||
let deleteManyStub,
|
||||
saveStub,
|
||||
findOneStub,
|
||||
userCompareStub,
|
||||
userSaveStub,
|
||||
userFindOneStub;
|
||||
let deleteManyStub, saveStub, findOneStub, userCompareStub, userSaveStub, userFindOneStub;
|
||||
let req, res;
|
||||
|
||||
beforeEach(function () {
|
||||
@@ -153,9 +144,7 @@ describe("recoveryModule", function () {
|
||||
it("should throw an error if the passwords match", async function () {
|
||||
findOneStub.resolves(mockRecoveryToken);
|
||||
saveStub.resolves();
|
||||
userFindOneStub = sinon
|
||||
.stub(User, "findOne")
|
||||
.returns(createQueryChain(mockUser, true));
|
||||
userFindOneStub = sinon.stub(User, "findOne").returns(createQueryChain(mockUser, true));
|
||||
try {
|
||||
await resetPassword(req, res);
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import sinon from "sinon";
|
||||
import {
|
||||
getAppSettings,
|
||||
updateAppSettings,
|
||||
} from "../../db/mongo/modules/settingsModule.js";
|
||||
import { getAppSettings, updateAppSettings } from "../../db/mongo/modules/settingsModule.js";
|
||||
import AppSettings from "../../db/models/AppSettings.js";
|
||||
|
||||
const mockAppSettings = {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import sinon from "sinon";
|
||||
import {
|
||||
createStatusPage,
|
||||
getStatusPageByUrl,
|
||||
} from "../../db/mongo/modules/statusPageModule.js";
|
||||
import { createStatusPage, getStatusPageByUrl } from "../../db/mongo/modules/statusPageModule.js";
|
||||
import StatusPage from "../../db/models/StatusPage.js";
|
||||
import { errorMessages } from "../../utils/messages.js";
|
||||
|
||||
|
||||
@@ -157,12 +157,7 @@ describe("userModule", function () {
|
||||
select: sinon.stub().resolves(mockUser),
|
||||
}),
|
||||
});
|
||||
const result = await updateUser(
|
||||
req,
|
||||
res,
|
||||
parseBooleanStub,
|
||||
generateAvatarImageStub
|
||||
);
|
||||
const result = await updateUser(req, res, parseBooleanStub, generateAvatarImageStub);
|
||||
expect(result).to.deep.equal(mockUser);
|
||||
});
|
||||
|
||||
@@ -173,12 +168,7 @@ describe("userModule", function () {
|
||||
select: sinon.stub().resolves(mockUser),
|
||||
}),
|
||||
});
|
||||
const result = await updateUser(
|
||||
req,
|
||||
res,
|
||||
parseBooleanStub,
|
||||
generateAvatarImageStub
|
||||
);
|
||||
const result = await updateUser(req, res, parseBooleanStub, generateAvatarImageStub);
|
||||
expect(result).to.deep.equal(mockUser);
|
||||
});
|
||||
|
||||
|
||||
@@ -48,15 +48,7 @@ describe("EmailService - Constructor", function () {
|
||||
});
|
||||
|
||||
it("should initialize template loaders and email transporter", function () {
|
||||
const emailService = new EmailService(
|
||||
settingsServiceMock,
|
||||
fsMock,
|
||||
pathMock,
|
||||
compileMock,
|
||||
mjml2htmlMock,
|
||||
nodemailerMock,
|
||||
loggerMock
|
||||
);
|
||||
const emailService = new EmailService(settingsServiceMock, fsMock, pathMock, compileMock, mjml2htmlMock, nodemailerMock, loggerMock);
|
||||
|
||||
// Verify that the settingsService is assigned correctly
|
||||
expect(emailService.settingsService).to.equal(settingsServiceMock);
|
||||
@@ -83,15 +75,7 @@ describe("EmailService - Constructor", function () {
|
||||
fsMock = {
|
||||
readFileSync: sinon.stub().throws(new Error("File read error")),
|
||||
};
|
||||
const emailService = new EmailService(
|
||||
settingsServiceMock,
|
||||
fsMock,
|
||||
pathMock,
|
||||
compileMock,
|
||||
mjml2htmlMock,
|
||||
nodemailerMock,
|
||||
loggerMock
|
||||
);
|
||||
const emailService = new EmailService(settingsServiceMock, fsMock, pathMock, compileMock, mjml2htmlMock, nodemailerMock, loggerMock);
|
||||
expect(loggerMock.error.called).to.be.true;
|
||||
expect(loggerMock.error.firstCall.args[0].message).to.equal("File read error");
|
||||
});
|
||||
@@ -139,15 +123,7 @@ describe("EmailService - buildAndSendEmail", function () {
|
||||
error: sinon.stub(),
|
||||
};
|
||||
|
||||
emailService = new EmailService(
|
||||
settingsServiceMock,
|
||||
fsMock,
|
||||
pathMock,
|
||||
compileMock,
|
||||
mjml2htmlMock,
|
||||
nodemailerMock,
|
||||
loggerMock
|
||||
);
|
||||
emailService = new EmailService(settingsServiceMock, fsMock, pathMock, compileMock, mjml2htmlMock, nodemailerMock, loggerMock);
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
@@ -155,12 +131,7 @@ describe("EmailService - buildAndSendEmail", function () {
|
||||
});
|
||||
|
||||
it("should build and send email successfully", async function () {
|
||||
const messageId = await emailService.buildAndSendEmail(
|
||||
"welcomeEmailTemplate",
|
||||
{},
|
||||
"recipient@example.com",
|
||||
"Welcome"
|
||||
);
|
||||
const messageId = await emailService.buildAndSendEmail("welcomeEmailTemplate", {}, "recipient@example.com", "Welcome");
|
||||
|
||||
expect(messageId).to.equal("12345");
|
||||
expect(nodemailerMock.createTransport().sendMail.calledOnce).to.be.true;
|
||||
@@ -169,24 +140,14 @@ describe("EmailService - buildAndSendEmail", function () {
|
||||
it("should log error if building HTML fails", async function () {
|
||||
mjml2htmlMock.throws(new Error("MJML error"));
|
||||
|
||||
const messageId = await emailService.buildAndSendEmail(
|
||||
"welcomeEmailTemplate",
|
||||
{},
|
||||
"recipient@example.com",
|
||||
"Welcome"
|
||||
);
|
||||
const messageId = await emailService.buildAndSendEmail("welcomeEmailTemplate", {}, "recipient@example.com", "Welcome");
|
||||
expect(loggerMock.error.calledOnce).to.be.true;
|
||||
expect(loggerMock.error.getCall(0).args[0].message).to.equal("MJML error");
|
||||
});
|
||||
|
||||
it("should log error if sending email fails", async function () {
|
||||
nodemailerMock.createTransport().sendMail.rejects(new Error("SMTP error"));
|
||||
await emailService.buildAndSendEmail(
|
||||
"welcomeEmailTemplate",
|
||||
{},
|
||||
"recipient@example.com",
|
||||
"Welcome"
|
||||
);
|
||||
await emailService.buildAndSendEmail("welcomeEmailTemplate", {}, "recipient@example.com", "Welcome");
|
||||
expect(loggerMock.error.calledOnce).to.be.true;
|
||||
expect(loggerMock.error.getCall(0).args[0].message).to.equal("SMTP error");
|
||||
});
|
||||
@@ -195,12 +156,7 @@ describe("EmailService - buildAndSendEmail", function () {
|
||||
mjml2htmlMock.throws(new Error("MJML error"));
|
||||
nodemailerMock.createTransport().sendMail.rejects(new Error("SMTP error"));
|
||||
|
||||
const messageId = await emailService.buildAndSendEmail(
|
||||
"welcomeEmailTemplate",
|
||||
{},
|
||||
"recipient@example.com",
|
||||
"Welcome"
|
||||
);
|
||||
const messageId = await emailService.buildAndSendEmail("welcomeEmailTemplate", {}, "recipient@example.com", "Welcome");
|
||||
|
||||
expect(messageId).to.be.undefined;
|
||||
expect(loggerMock.error.calledTwice).to.be.true;
|
||||
|
||||
@@ -52,13 +52,7 @@ class WorkerStub {
|
||||
}
|
||||
|
||||
describe("JobQueue", function () {
|
||||
let settingsService,
|
||||
logger,
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
jobQueue;
|
||||
let settingsService, logger, db, networkService, statusService, notificationService, jobQueue;
|
||||
|
||||
beforeEach(async function () {
|
||||
settingsService = { getSettings: sinon.stub() };
|
||||
@@ -71,16 +65,7 @@ describe("JobQueue", function () {
|
||||
getMaintenanceWindowsByMonitorId: sinon.stub().returns([]),
|
||||
};
|
||||
networkService = { getStatus: sinon.stub() };
|
||||
jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
jobQueue = await JobQueue.createJobQueue(db, networkService, statusService, notificationService, settingsService, logger, QueueStub, WorkerStub);
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
@@ -327,9 +312,7 @@ describe("JobQueue", function () {
|
||||
const handler = jobQueue.createJobHandler();
|
||||
await handler({ data: { _id: 1 } });
|
||||
expect(logger.info.calledOnce).to.be.true;
|
||||
expect(logger.info.firstCall.args[0].message).to.equal(
|
||||
"Monitor 1 is in maintenance window"
|
||||
);
|
||||
expect(logger.info.firstCall.args[0].message).to.equal("Monitor 1 is in maintenance window");
|
||||
});
|
||||
|
||||
it("should return if status has not changed", async function () {
|
||||
@@ -362,9 +345,7 @@ describe("JobQueue", function () {
|
||||
WorkerStub
|
||||
);
|
||||
jobQueue.isInMaintenanceWindow = sinon.stub().returns(false);
|
||||
statusService.updateStatus = sinon
|
||||
.stub()
|
||||
.returns({ statusChanged: true, prevStatus: undefined });
|
||||
statusService.updateStatus = sinon.stub().returns({ statusChanged: true, prevStatus: undefined });
|
||||
const handler = jobQueue.createJobHandler();
|
||||
await handler({ data: { _id: 1 } });
|
||||
expect(jobQueue.notificationService.handleNotifications.notCalled).to.be.true;
|
||||
@@ -382,9 +363,7 @@ describe("JobQueue", function () {
|
||||
WorkerStub
|
||||
);
|
||||
jobQueue.isInMaintenanceWindow = sinon.stub().returns(false);
|
||||
statusService.updateStatus = sinon
|
||||
.stub()
|
||||
.returns({ statusChanged: true, prevStatus: false });
|
||||
statusService.updateStatus = sinon.stub().returns({ statusChanged: true, prevStatus: false });
|
||||
const handler = jobQueue.createJobHandler();
|
||||
await handler({ data: { _id: 1 } });
|
||||
expect(jobQueue.notificationService.handleNotifications.calledOnce).to.be.true;
|
||||
|
||||
@@ -26,9 +26,7 @@ describe("Network Service", function () {
|
||||
};
|
||||
ping = {
|
||||
promise: {
|
||||
probe: sinon
|
||||
.stub()
|
||||
.resolves({ response: { alive: true }, responseTime: 100, alive: true }),
|
||||
probe: sinon.stub().resolves({ response: { alive: true }, responseTime: 100, alive: true }),
|
||||
},
|
||||
};
|
||||
logger = { error: sinon.stub() };
|
||||
@@ -73,9 +71,7 @@ describe("Network Service", function () {
|
||||
|
||||
it("should return a response object if ping unsuccessful", async function () {
|
||||
const error = new Error("Test error");
|
||||
networkService.timeRequest = sinon
|
||||
.stub()
|
||||
.resolves({ response: null, responseTime: 1, error });
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const pingResult = await networkService.requestPing({
|
||||
data: { url: "http://test.com", _id: "123" },
|
||||
});
|
||||
@@ -113,9 +109,7 @@ describe("Network Service", function () {
|
||||
it("should return a response object if http unsuccessful", async function () {
|
||||
const error = new Error("Test error");
|
||||
error.response = { status: 404 };
|
||||
networkService.timeRequest = sinon
|
||||
.stub()
|
||||
.resolves({ response: null, responseTime: 1, error });
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "http" } };
|
||||
const httpResult = await networkService.requestHttp(job);
|
||||
expect(httpResult.monitorId).to.equal("123");
|
||||
@@ -128,9 +122,7 @@ describe("Network Service", function () {
|
||||
it("should return a response object if http unsuccessful with unknown code", async function () {
|
||||
const error = new Error("Test error");
|
||||
error.response = {};
|
||||
networkService.timeRequest = sinon
|
||||
.stub()
|
||||
.resolves({ response: null, responseTime: 1, error });
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "http" } };
|
||||
const httpResult = await networkService.requestHttp(job);
|
||||
expect(httpResult.monitorId).to.equal("123");
|
||||
@@ -167,9 +159,7 @@ describe("Network Service", function () {
|
||||
it("should return a response object if pagespeed unsuccessful", async function () {
|
||||
const error = new Error("Test error");
|
||||
error.response = { status: 404 };
|
||||
networkService.timeRequest = sinon
|
||||
.stub()
|
||||
.resolves({ response: null, responseTime: 1, error });
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "pagespeed" } };
|
||||
const pagespeedResult = await networkService.requestPagespeed(job);
|
||||
expect(pagespeedResult.monitorId).to.equal("123");
|
||||
@@ -182,9 +172,7 @@ describe("Network Service", function () {
|
||||
it("should return a response object if pagespeed unsuccessful with an unknown code", async function () {
|
||||
const error = new Error("Test error");
|
||||
error.response = {};
|
||||
networkService.timeRequest = sinon
|
||||
.stub()
|
||||
.resolves({ response: null, responseTime: 1, error });
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "pagespeed" } };
|
||||
const pagespeedResult = await networkService.requestPagespeed(job);
|
||||
expect(pagespeedResult.monitorId).to.equal("123");
|
||||
@@ -237,9 +225,7 @@ describe("Network Service", function () {
|
||||
it("should return a response object if hardware unsuccessful", async function () {
|
||||
const error = new Error("Test error");
|
||||
error.response = { status: 404 };
|
||||
networkService.timeRequest = sinon
|
||||
.stub()
|
||||
.resolves({ response: null, responseTime: 1, error });
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "hardware" } };
|
||||
const httpResult = await networkService.requestHardware(job);
|
||||
expect(httpResult.monitorId).to.equal("123");
|
||||
@@ -252,9 +238,7 @@ describe("Network Service", function () {
|
||||
it("should return a response object if hardware unsuccessful with unknown code", async function () {
|
||||
const error = new Error("Test error");
|
||||
error.response = {};
|
||||
networkService.timeRequest = sinon
|
||||
.stub()
|
||||
.resolves({ response: null, responseTime: 1, error });
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "hardware" } };
|
||||
const httpResult = await networkService.requestHardware(job);
|
||||
expect(httpResult.monitorId).to.equal("123");
|
||||
|
||||
@@ -43,10 +43,7 @@ describe("NotificationService", function () {
|
||||
await notificationService.sendEmail(networkResponse, address);
|
||||
expect(notificationService.emailService.buildAndSendEmail.calledOnce).to.be.true;
|
||||
expect(
|
||||
notificationService.emailService.buildAndSendEmail.calledWith(
|
||||
"serverIsUpTemplate",
|
||||
{ monitor: "Test Monitor", url: "http://test.com" }
|
||||
)
|
||||
notificationService.emailService.buildAndSendEmail.calledWith("serverIsUpTemplate", { monitor: "Test Monitor", url: "http://test.com" })
|
||||
);
|
||||
});
|
||||
|
||||
@@ -132,22 +129,14 @@ describe("NotificationService", function () {
|
||||
|
||||
it("should send an email notification with Hardware Template", async function () {
|
||||
emailService.buildAndSendEmail.resolves(true);
|
||||
const res = await notificationService.sendHardwareEmail(
|
||||
networkResponse,
|
||||
address,
|
||||
alerts
|
||||
);
|
||||
const res = await notificationService.sendHardwareEmail(networkResponse, address, alerts);
|
||||
expect(res).to.be.true;
|
||||
});
|
||||
|
||||
it("should return false if no alerts are provided", async function () {
|
||||
alerts = [];
|
||||
emailService.buildAndSendEmail.resolves(true);
|
||||
const res = await notificationService.sendHardwareEmail(
|
||||
networkResponse,
|
||||
address,
|
||||
alerts
|
||||
);
|
||||
const res = await notificationService.sendHardwareEmail(networkResponse, address, alerts);
|
||||
expect(res).to.be.false;
|
||||
});
|
||||
});
|
||||
@@ -172,9 +161,7 @@ describe("NotificationService", function () {
|
||||
});
|
||||
|
||||
it("should handle status notifications", async function () {
|
||||
db.getNotificationsByMonitorId.resolves([
|
||||
{ type: "email", address: "test@test.com" },
|
||||
]);
|
||||
db.getNotificationsByMonitorId.resolves([{ type: "email", address: "test@test.com" }]);
|
||||
const res = await notificationService.handleStatusNotifications(networkResponse);
|
||||
expect(res).to.be.true;
|
||||
});
|
||||
@@ -247,15 +234,13 @@ describe("NotificationService", function () {
|
||||
describe("it should return false if no thresholds are set", function () {
|
||||
it("should return false if no thresholds are set", async function () {
|
||||
networkResponse.monitor.thresholds = undefined;
|
||||
const res =
|
||||
await notificationService.handleHardwareNotifications(networkResponse);
|
||||
const res = await notificationService.handleHardwareNotifications(networkResponse);
|
||||
expect(res).to.be.false;
|
||||
});
|
||||
|
||||
it("should return false if metrics are null", async function () {
|
||||
networkResponse.payload.data = null;
|
||||
const res =
|
||||
await notificationService.handleHardwareNotifications(networkResponse);
|
||||
const res = await notificationService.handleHardwareNotifications(networkResponse);
|
||||
expect(res).to.be.false;
|
||||
});
|
||||
|
||||
@@ -271,8 +256,7 @@ describe("NotificationService", function () {
|
||||
save: sinon.stub().resolves(),
|
||||
},
|
||||
]);
|
||||
const res =
|
||||
await notificationService.handleHardwareNotifications(networkResponse);
|
||||
const res = await notificationService.handleHardwareNotifications(networkResponse);
|
||||
expect(res).to.be.true;
|
||||
});
|
||||
|
||||
@@ -293,8 +277,7 @@ describe("NotificationService", function () {
|
||||
usage_memory: 0.01,
|
||||
usage_disk: 0.01,
|
||||
};
|
||||
const res =
|
||||
await notificationService.handleHardwareNotifications(networkResponse);
|
||||
const res = await notificationService.handleHardwareNotifications(networkResponse);
|
||||
expect(res).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,9 +13,7 @@ describe("SettingsService", function () {
|
||||
sandbox.stub(process.env, "JWT_SECRET").value("secret");
|
||||
sandbox.stub(process.env, "REFRESH_TOKEN_SECRET").value("refreshSecret");
|
||||
sandbox.stub(process.env, "DB_TYPE").value("postgres");
|
||||
sandbox
|
||||
.stub(process.env, "DB_CONNECTION_STRING")
|
||||
.value("postgres://user:pass@localhost/db");
|
||||
sandbox.stub(process.env, "DB_CONNECTION_STRING").value("postgres://user:pass@localhost/db");
|
||||
sandbox.stub(process.env, "REDIS_HOST").value("localhost");
|
||||
sandbox.stub(process.env, "REDIS_PORT").value("6379");
|
||||
sandbox.stub(process.env, "TOKEN_TTL").value("3600");
|
||||
|
||||
@@ -73,9 +73,7 @@ describe("StatusService", () => {
|
||||
});
|
||||
|
||||
it("should return {statusChanged: true} if status has changed from down to up", async function () {
|
||||
statusService.db.getMonitorById = sinon
|
||||
.stub()
|
||||
.returns({ status: false, save: sinon.stub() });
|
||||
statusService.db.getMonitorById = sinon.stub().returns({ status: false, save: sinon.stub() });
|
||||
const result = await statusService.updateStatus({
|
||||
monitorId: "test",
|
||||
status: true,
|
||||
@@ -87,9 +85,7 @@ describe("StatusService", () => {
|
||||
});
|
||||
|
||||
it("should return {statusChanged: true} if status has changed from up to down", async function () {
|
||||
statusService.db.getMonitorById = sinon
|
||||
.stub()
|
||||
.returns({ status: true, save: sinon.stub() });
|
||||
statusService.db.getMonitorById = sinon.stub().returns({ status: true, save: sinon.stub() });
|
||||
const result = await statusService.updateStatus({
|
||||
monitorId: "test",
|
||||
status: false,
|
||||
|
||||
@@ -51,13 +51,7 @@ describe("NormalizeData", function () {
|
||||
|
||||
describe("calculatePercentile", function () {
|
||||
it("should return the lower value when upper is greater than or equal to the length of the sorted array", function () {
|
||||
const checks = [
|
||||
{ responseTime: 10 },
|
||||
{ responseTime: 20 },
|
||||
{ responseTime: 30 },
|
||||
{ responseTime: 40 },
|
||||
{ responseTime: 50 },
|
||||
];
|
||||
const checks = [{ responseTime: 10 }, { responseTime: 20 }, { responseTime: 30 }, { responseTime: 40 }, { responseTime: 50 }];
|
||||
|
||||
const percentile = 100;
|
||||
const result = calculatePercentile(checks, percentile);
|
||||
|
||||
@@ -12,9 +12,7 @@ describe("imageProcessing - GenerateAvatarImage", function () {
|
||||
// Stub the sharp function
|
||||
const toBufferStub = sinon.stub().resolves(Buffer.from("resized image buffer"));
|
||||
const resizeStub = sinon.stub().returns({ toBuffer: toBufferStub });
|
||||
const sharpStub = sinon
|
||||
.stub(sharp.prototype, "resize")
|
||||
.returns({ toBuffer: toBufferStub });
|
||||
const sharpStub = sinon.stub(sharp.prototype, "resize").returns({ toBuffer: toBufferStub });
|
||||
|
||||
const result = await GenerateAvatarImage(file);
|
||||
|
||||
@@ -38,9 +36,7 @@ describe("imageProcessing - GenerateAvatarImage", function () {
|
||||
// Stub the sharp function to throw an error
|
||||
const toBufferStub = sinon.stub().rejects(new Error("Resizing failed"));
|
||||
const resizeStub = sinon.stub().returns({ toBuffer: toBufferStub });
|
||||
const sharpStub = sinon
|
||||
.stub(sharp.prototype, "resize")
|
||||
.returns({ toBuffer: toBufferStub });
|
||||
const sharpStub = sinon.stub(sharp.prototype, "resize").returns({ toBuffer: toBufferStub });
|
||||
|
||||
try {
|
||||
await GenerateAvatarImage(file);
|
||||
|
||||
@@ -3,25 +3,19 @@ describe("Messages", function () {
|
||||
describe("messages - errorMessages", function () {
|
||||
it("should have a DB_FIND_MONITOR_BY_ID function", function () {
|
||||
const monitorId = "12345";
|
||||
expect(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)).to.equal(
|
||||
`Monitor with id ${monitorId} not found`
|
||||
);
|
||||
expect(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)).to.equal(`Monitor with id ${monitorId} not found`);
|
||||
});
|
||||
|
||||
it("should have a DB_DELETE_CHECKS function", function () {
|
||||
const monitorId = "12345";
|
||||
expect(errorMessages.DB_DELETE_CHECKS(monitorId)).to.equal(
|
||||
`No checks found for monitor with id ${monitorId}`
|
||||
);
|
||||
expect(errorMessages.DB_DELETE_CHECKS(monitorId)).to.equal(`No checks found for monitor with id ${monitorId}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("messages - successMessages", function () {
|
||||
it("should have a MONITOR_GET_BY_USER_ID function", function () {
|
||||
const userId = "12345";
|
||||
expect(successMessages.MONITOR_GET_BY_USER_ID(userId)).to.equal(
|
||||
`Got monitor for ${userId} successfully"`
|
||||
);
|
||||
expect(successMessages.MONITOR_GET_BY_USER_ID(userId)).to.equal(`Got monitor for ${userId} successfully"`);
|
||||
});
|
||||
|
||||
// Add more tests for other success messages as needed
|
||||
|
||||
@@ -15,9 +15,7 @@ const calculatePercentileUptimeDetails = (arr, percentile) => {
|
||||
const upper = lower + 1;
|
||||
const weight = index % 1;
|
||||
if (upper >= sorted.length) return sorted[lower].avgResponseTime;
|
||||
return (
|
||||
sorted[lower].avgResponseTime * (1 - weight) + sorted[upper].avgResponseTime * weight
|
||||
);
|
||||
return sorted[lower].avgResponseTime * (1 - weight) + sorted[upper].avgResponseTime * weight;
|
||||
};
|
||||
|
||||
const NormalizeData = (checks, rangeMin, rangeMax) => {
|
||||
@@ -28,15 +26,11 @@ const NormalizeData = (checks, rangeMin, rangeMax) => {
|
||||
const normalizedChecks = checks.map((check) => {
|
||||
const originalResponseTime = check.responseTime;
|
||||
// Normalize the response time between 1 and 100
|
||||
let normalizedResponseTime =
|
||||
rangeMin + ((check.responseTime - min) * (rangeMax - rangeMin)) / (max - min);
|
||||
let normalizedResponseTime = rangeMin + ((check.responseTime - min) * (rangeMax - rangeMin)) / (max - min);
|
||||
|
||||
// Put a floor on the response times so we don't have extreme outliers
|
||||
// Better visuals
|
||||
normalizedResponseTime = Math.max(
|
||||
rangeMin,
|
||||
Math.min(rangeMax, normalizedResponseTime)
|
||||
);
|
||||
normalizedResponseTime = Math.max(rangeMin, Math.min(rangeMax, normalizedResponseTime));
|
||||
return {
|
||||
...check,
|
||||
responseTime: normalizedResponseTime,
|
||||
@@ -60,15 +54,11 @@ const NormalizeDataUptimeDetails = (checks, rangeMin, rangeMax) => {
|
||||
const normalizedChecks = checks.map((check) => {
|
||||
const originalResponseTime = check.avgResponseTime;
|
||||
// Normalize the response time between 1 and 100
|
||||
let normalizedResponseTime =
|
||||
rangeMin + ((check.avgResponseTime - min) * (rangeMax - rangeMin)) / (max - min);
|
||||
let normalizedResponseTime = rangeMin + ((check.avgResponseTime - min) * (rangeMax - rangeMin)) / (max - min);
|
||||
|
||||
// Put a floor on the response times so we don't have extreme outliers
|
||||
// Better visuals
|
||||
normalizedResponseTime = Math.max(
|
||||
rangeMin,
|
||||
Math.min(rangeMax, normalizedResponseTime)
|
||||
);
|
||||
normalizedResponseTime = Math.max(rangeMin, Math.min(rangeMax, normalizedResponseTime));
|
||||
return {
|
||||
...check,
|
||||
avgResponseTime: normalizedResponseTime,
|
||||
@@ -107,10 +97,4 @@ const safelyParseFloat = (value, defaultValue = 0) => {
|
||||
return parsedValue;
|
||||
};
|
||||
|
||||
export {
|
||||
safelyParseFloat,
|
||||
calculatePercentile,
|
||||
NormalizeData,
|
||||
calculatePercentileUptimeDetails,
|
||||
NormalizeDataUptimeDetails,
|
||||
};
|
||||
export { safelyParseFloat, calculatePercentile, NormalizeData, calculatePercentileUptimeDetails, NormalizeDataUptimeDetails };
|
||||
@@ -0,0 +1,77 @@
|
||||
class AppError extends Error {
|
||||
constructor(message, status = 500, service = null, method = null, details = null) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.service = service;
|
||||
this.method = method;
|
||||
this.details = details;
|
||||
|
||||
Error.captureStackTrace(this, this.constructor);
|
||||
}
|
||||
}
|
||||
|
||||
export const createError = (message, status = 500, service = null, method = null, details = null) => {
|
||||
return new AppError(message, status, service, method, details);
|
||||
};
|
||||
|
||||
export const createValidationError = (message, details = null, service = null, method = null) => {
|
||||
return createError(message, 422, service, method, details);
|
||||
};
|
||||
|
||||
export const createAuthError = (message, details = null, service = null, method = null) => {
|
||||
return createError(message, 401, service, method, details);
|
||||
};
|
||||
|
||||
export const createForbiddenError = (message, details = null, service = null, method = null) => {
|
||||
return createError(message, 403, service, method, details);
|
||||
};
|
||||
|
||||
export const createNotFoundError = (message, details = null, service = null, method = null) => {
|
||||
return createError(message, 404, service, method, details);
|
||||
};
|
||||
|
||||
export const createConflictError = (message, details = null, service = null, method = null) => {
|
||||
return createError(message, 409, service, method, details);
|
||||
};
|
||||
|
||||
export const createServerError = (message, details = null, service = null, method = null) => {
|
||||
return createError(message, 500, service, method, details);
|
||||
};
|
||||
|
||||
export const asyncHandler = (fn, serviceName, methodName) => {
|
||||
return async (req, res, next) => {
|
||||
try {
|
||||
await fn(req, res, next);
|
||||
} catch (error) {
|
||||
// Handle validation errors
|
||||
if (error.isJoi || error.name === "ValidationError") {
|
||||
const validationError = createValidationError(error.message, error.details, serviceName, methodName);
|
||||
return next(validationError);
|
||||
}
|
||||
|
||||
if (error instanceof AppError) {
|
||||
error.service = error.service || serviceName;
|
||||
error.method = error.method || methodName;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
if (error.code === "23505") {
|
||||
const appError = createConflictError("Resource already exists", {
|
||||
originalError: error.message,
|
||||
code: error.code,
|
||||
});
|
||||
appError.service = serviceName;
|
||||
appError.method = methodName;
|
||||
return next(appError);
|
||||
}
|
||||
|
||||
// For unknown errors, create a server error
|
||||
const appError = createServerError(error.message || "An unexpected error occurred", { originalError: error.message, stack: error.stack });
|
||||
appError.service = serviceName;
|
||||
appError.method = methodName;
|
||||
appError.stack = error.stack; // Preserve original stack
|
||||
|
||||
return next(appError);
|
||||
}
|
||||
};
|
||||
};
|
||||
+35
-42
@@ -6,43 +6,41 @@ class Logger {
|
||||
constructor() {
|
||||
this.logCache = [];
|
||||
this.maxCacheSize = 1000;
|
||||
const consoleFormat = format.printf(
|
||||
({ level, message, service, method, details, timestamp, stack }) => {
|
||||
if (message instanceof Object) {
|
||||
message = JSON.stringify(message, null, 2);
|
||||
}
|
||||
|
||||
if (details instanceof Object) {
|
||||
details = JSON.stringify(details, null, 2);
|
||||
}
|
||||
let msg = `${timestamp} ${level}:`;
|
||||
service && (msg += ` [${service}]`);
|
||||
method && (msg += `(${method})`);
|
||||
message && (msg += ` ${message}`);
|
||||
details && (msg += ` (details: ${details})`);
|
||||
|
||||
if (typeof stack !== "undefined") {
|
||||
const stackTrace = stack
|
||||
?.split("\n")
|
||||
.slice(1) // Remove first line (error message)
|
||||
.map((line) => {
|
||||
const match = line.match(/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);
|
||||
if (match) {
|
||||
return {
|
||||
function: match[1],
|
||||
file: match[2],
|
||||
line: parseInt(match[3]),
|
||||
column: parseInt(match[4]),
|
||||
};
|
||||
}
|
||||
return line.trim();
|
||||
});
|
||||
stack && (msg += ` (stack: ${JSON.stringify(stackTrace, null, 2)})`);
|
||||
}
|
||||
|
||||
return msg;
|
||||
const consoleFormat = format.printf(({ level, message, service, method, details, timestamp, stack }) => {
|
||||
if (message instanceof Object) {
|
||||
message = JSON.stringify(message, null, 2);
|
||||
}
|
||||
);
|
||||
|
||||
if (details instanceof Object) {
|
||||
details = JSON.stringify(details, null, 2);
|
||||
}
|
||||
let msg = `${timestamp} ${level}:`;
|
||||
service && (msg += ` [${service}]`);
|
||||
method && (msg += `(${method})`);
|
||||
message && (msg += ` ${message}`);
|
||||
details && (msg += ` (details: ${details})`);
|
||||
|
||||
if (typeof stack !== "undefined") {
|
||||
const stackTrace = stack
|
||||
?.split("\n")
|
||||
.slice(1) // Remove first line (error message)
|
||||
.map((line) => {
|
||||
const match = line.match(/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);
|
||||
if (match) {
|
||||
return {
|
||||
function: match[1],
|
||||
file: match[2],
|
||||
line: parseInt(match[3]),
|
||||
column: parseInt(match[4]),
|
||||
};
|
||||
}
|
||||
return line.trim();
|
||||
});
|
||||
stack && (msg += ` (stack: ${JSON.stringify(stackTrace, null, 2)})`);
|
||||
}
|
||||
|
||||
return msg;
|
||||
});
|
||||
|
||||
const logLevel = process.env.LOG_LEVEL || "info";
|
||||
|
||||
@@ -51,12 +49,7 @@ class Logger {
|
||||
format: format.combine(format.timestamp()),
|
||||
transports: [
|
||||
new transports.Console({
|
||||
format: format.combine(
|
||||
format.colorize(),
|
||||
format.prettyPrint(),
|
||||
format.json(),
|
||||
consoleFormat
|
||||
),
|
||||
format: format.combine(format.colorize(), format.prettyPrint(), format.json(), consoleFormat),
|
||||
}),
|
||||
new transports.File({
|
||||
format: format.combine(format.json()),
|
||||
|
||||
@@ -6,12 +6,7 @@
|
||||
const ParseBoolean = (value) => {
|
||||
if (value === true || value === "true") {
|
||||
return true;
|
||||
} else if (
|
||||
value === false ||
|
||||
value === "false" ||
|
||||
value === null ||
|
||||
value === undefined
|
||||
) {
|
||||
} else if (value === false || value === "false" || value === null || value === undefined) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -21,8 +16,7 @@ const getTokenFromHeaders = (headers) => {
|
||||
if (!authorizationHeader) throw new Error("No auth headers");
|
||||
|
||||
const parts = authorizationHeader.split(" ");
|
||||
if (parts.length !== 2 || parts[0] !== "Bearer")
|
||||
throw new Error("Invalid auth headers");
|
||||
if (parts.length !== 2 || parts[0] !== "Bearer") throw new Error("Invalid auth headers");
|
||||
|
||||
return parts[1];
|
||||
};
|
||||
|
||||
+90
-32
@@ -1,4 +1,5 @@
|
||||
import joi from "joi";
|
||||
import { ROLES, VALID_ROLES } from "../../client/src/Utils/roleUtils.js";
|
||||
|
||||
//****************************************
|
||||
// Custom Validators
|
||||
@@ -7,9 +8,7 @@ import joi from "joi";
|
||||
const roleValidatior = (role) => (value, helpers) => {
|
||||
const hasRole = role.some((role) => value.includes(role));
|
||||
if (!hasRole) {
|
||||
throw new joi.ValidationError(
|
||||
`You do not have the required authorization. Required roles: ${role.join(", ")}`
|
||||
);
|
||||
throw new joi.ValidationError(`You do not have the required authorization. Required roles: ${role.join(", ")}`);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
@@ -58,10 +57,6 @@ const registrationBodyValidation = joi.object({
|
||||
inviteToken: joi.string().allow("").required(),
|
||||
});
|
||||
|
||||
const editUserParamValidation = joi.object({
|
||||
userId: joi.string().required(),
|
||||
});
|
||||
|
||||
const editUserBodyValidation = joi.object({
|
||||
firstName: nameValidation.required(),
|
||||
lastName: nameValidation.required(),
|
||||
@@ -134,11 +129,7 @@ const getMonitorsByTeamIdQueryValidation = joi.object({
|
||||
.alternatives()
|
||||
.try(
|
||||
joi.string().valid("http", "ping", "pagespeed", "docker", "hardware", "port"),
|
||||
joi
|
||||
.array()
|
||||
.items(
|
||||
joi.string().valid("http", "ping", "pagespeed", "docker", "hardware", "port")
|
||||
)
|
||||
joi.array().items(joi.string().valid("http", "ping", "pagespeed", "docker", "hardware", "port"))
|
||||
),
|
||||
page: joi.number(),
|
||||
rowsPerPage: joi.number(),
|
||||
@@ -168,7 +159,43 @@ const createMonitorBodyValidation = joi.object({
|
||||
name: joi.string().required(),
|
||||
description: joi.string().required(),
|
||||
type: joi.string().required(),
|
||||
url: joi.string().required(),
|
||||
url: joi
|
||||
.string()
|
||||
.required()
|
||||
.custom((value, helpers) => {
|
||||
// 1. Standard URLs: must have protocol and pass canParse()
|
||||
if (/^(https?:\/\/)/.test(value)) {
|
||||
if (typeof URL !== "undefined" && typeof URL.canParse === "function" && URL.canParse(value)) {
|
||||
return value;
|
||||
}
|
||||
// else, it's a malformed URL with protocol
|
||||
return helpers.error("string.invalidUrl");
|
||||
}
|
||||
|
||||
// 2. Docker/internal hostnames (no protocol)
|
||||
if (/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?(:\d{1,5})?$/.test(value)) {
|
||||
if (value.includes("..")) {
|
||||
return helpers.error("string.invalidUrl");
|
||||
}
|
||||
// Split by dot, check each label
|
||||
const labels = value.split(":")[0].split(".");
|
||||
for (const label of labels) {
|
||||
if (!label) return helpers.error("string.invalidUrl");
|
||||
if (label.startsWith("-") || label.endsWith("-")) {
|
||||
return helpers.error("string.invalidUrl");
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// 3. Everything else is invalid
|
||||
return helpers.error("string.invalidUrl");
|
||||
})
|
||||
.messages({
|
||||
"string.empty": "This field is required.",
|
||||
"string.uri": "The URL you provided is not valid.",
|
||||
"string.invalidUrl": "Please enter a valid URL, hostname, or container name (with optional port).",
|
||||
}),
|
||||
ignoreTlsErrors: joi.boolean().default(false),
|
||||
port: joi.number(),
|
||||
isActive: joi.boolean(),
|
||||
@@ -454,8 +481,7 @@ const createStatusPageBodyValidation = joi.object({
|
||||
.pattern(/^[a-zA-Z0-9_-]+$/) // Only allow alphanumeric, underscore, and hyphen
|
||||
.required()
|
||||
.messages({
|
||||
"string.pattern.base":
|
||||
"URL can only contain letters, numbers, underscores, and hyphens",
|
||||
"string.pattern.base": "URL can only contain letters, numbers, underscores, and hyphens",
|
||||
}),
|
||||
timezone: joi.string().optional(),
|
||||
color: joi.string().optional(),
|
||||
@@ -485,13 +511,9 @@ const imageValidation = joi
|
||||
fieldname: joi.string().required(),
|
||||
originalname: joi.string().required(),
|
||||
encoding: joi.string().required(),
|
||||
mimetype: joi
|
||||
.string()
|
||||
.valid("image/jpeg", "image/png", "image/jpg")
|
||||
.required()
|
||||
.messages({
|
||||
"string.valid": "File must be a valid image (jpeg, jpg, or png)",
|
||||
}),
|
||||
mimetype: joi.string().valid("image/jpeg", "image/png", "image/jpg").required().messages({
|
||||
"string.valid": "File must be a valid image (jpeg, jpg, or png)",
|
||||
}),
|
||||
size: joi.number().max(3145728).required().messages({
|
||||
"number.max": "File size must be less than 3MB",
|
||||
}),
|
||||
@@ -577,6 +599,13 @@ const createNotificationBodyValidation = joi.object({
|
||||
"string.empty": "Notification name is required",
|
||||
"any.required": "Notification name is required",
|
||||
}),
|
||||
|
||||
type: joi.string().valid("email", "webhook", "slack", "discord", "pager_duty").required().messages({
|
||||
"string.empty": "Notification type is required",
|
||||
"any.required": "Notification type is required",
|
||||
"any.only": "Notification type must be email, webhook, or pager_duty",
|
||||
}),
|
||||
|
||||
address: joi.when("type", {
|
||||
is: "email",
|
||||
then: joi.string().email().required().messages({
|
||||
@@ -584,16 +613,12 @@ const createNotificationBodyValidation = joi.object({
|
||||
"any.required": "E-mail address is required",
|
||||
"string.email": "Please enter a valid e-mail address",
|
||||
}),
|
||||
}),
|
||||
type: joi
|
||||
.string()
|
||||
.valid("email", "webhook", "slack", "discord", "pager_duty")
|
||||
.required()
|
||||
.messages({
|
||||
"string.empty": "Notification type is required",
|
||||
"any.required": "Notification type is required",
|
||||
"any.only": "Notification type must be email, webhook, or pager_duty",
|
||||
otherwise: joi.string().uri().required().messages({
|
||||
"string.empty": "Webhook URL cannot be empty",
|
||||
"any.required": "Webhook URL is required",
|
||||
"string.uri": "Please enter a valid Webhook URL",
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
//****************************************
|
||||
@@ -628,6 +653,36 @@ const sendTestEmailBodyValidation = joi.object({
|
||||
systemEmailTLSServername: joi.string().allow("").optional(),
|
||||
});
|
||||
|
||||
const getUserByIdParamValidation = joi.object({
|
||||
userId: joi.string().required(),
|
||||
});
|
||||
|
||||
const editUserByIdParamValidation = joi.object({
|
||||
userId: joi.string().required(),
|
||||
});
|
||||
|
||||
const editUserByIdBodyValidation = joi.object({
|
||||
firstName: nameValidation.required(),
|
||||
lastName: nameValidation.required(),
|
||||
email: joi.string().email().required(),
|
||||
role: joi
|
||||
.array()
|
||||
.items(joi.string().valid(...VALID_ROLES))
|
||||
.min(1)
|
||||
.required(),
|
||||
});
|
||||
|
||||
const editSuperadminUserByIdBodyValidation = joi.object({
|
||||
firstName: nameValidation.required(),
|
||||
lastName: nameValidation.required(),
|
||||
email: joi.string().email().required(),
|
||||
role: joi
|
||||
.array()
|
||||
.items(joi.string().valid(...VALID_ROLES, ROLES.SUPERADMIN))
|
||||
.min(1)
|
||||
.required(),
|
||||
});
|
||||
|
||||
export {
|
||||
roleValidatior,
|
||||
loginValidation,
|
||||
@@ -652,7 +707,6 @@ export {
|
||||
editMonitorBodyValidation,
|
||||
pauseMonitorParamValidation,
|
||||
getMonitorURLByQueryValidation,
|
||||
editUserParamValidation,
|
||||
editUserBodyValidation,
|
||||
createAlertParamValidation,
|
||||
createAlertBodyValidation,
|
||||
@@ -696,4 +750,8 @@ export {
|
||||
webhookConfigValidation,
|
||||
createAnnouncementValidation,
|
||||
sendTestEmailBodyValidation,
|
||||
getUserByIdParamValidation,
|
||||
editUserByIdParamValidation,
|
||||
editUserByIdBodyValidation,
|
||||
editSuperadminUserByIdBodyValidation,
|
||||
};
|
||||
Reference in new issue
Block a user