Merge pull request #978 from bluewave-labs/fix/be/prettier-baseline

Format all files on BE with perttier config
This commit is contained in:
Alexander Holliday authored and GitHub committed 2024-10-18 10:03:18 +08:00
commit df74aba6ca
57 files changed
+8337 -8345

No files matched your search

+9 -9
View File
@@ -1,15 +1,15 @@
const PORT = 5000; const PORT = 5000;
const connectDbAndRunServer = async (app, db) => { const connectDbAndRunServer = async (app, db) => {
try { try {
await db.connect(); await db.connect();
app.listen(PORT, () => { app.listen(PORT, () => {
console.log(`server started on port:${PORT}`); console.log(`server started on port:${PORT}`);
}); });
} catch (error) { } catch (error) {
console.log("Failed to connect to DB"); console.log("Failed to connect to DB");
console.error(error); console.error(error);
} }
}; };
export { connectDbAndRunServer }; export { connectDbAndRunServer };
+119 -119
View File
@@ -1,13 +1,13 @@
import { import {
createCheckParamValidation, createCheckParamValidation,
createCheckBodyValidation, createCheckBodyValidation,
getChecksParamValidation, getChecksParamValidation,
getChecksQueryValidation, getChecksQueryValidation,
getTeamChecksParamValidation, getTeamChecksParamValidation,
getTeamChecksQueryValidation, getTeamChecksQueryValidation,
deleteChecksParamValidation, deleteChecksParamValidation,
deleteChecksByTeamIdParamValidation, deleteChecksByTeamIdParamValidation,
updateChecksTTLBodyValidation, updateChecksTTLBodyValidation,
} from "../validation/joi.js"; } from "../validation/joi.js";
import { successMessages } from "../utils/messages.js"; import { successMessages } from "../utils/messages.js";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
@@ -17,138 +17,138 @@ import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "checkController"; const SERVICE_NAME = "checkController";
const createCheck = async (req, res, next) => { const createCheck = async (req, res, next) => {
try { try {
await createCheckParamValidation.validateAsync(req.params); await createCheckParamValidation.validateAsync(req.params);
await createCheckBodyValidation.validateAsync(req.body); await createCheckBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const checkData = { ...req.body }; const checkData = { ...req.body };
const check = await req.db.createCheck(checkData); const check = await req.db.createCheck(checkData);
return res return res
.status(200) .status(200)
.json({ success: true, msg: successMessages.CHECK_CREATE, data: check }); .json({ success: true, msg: successMessages.CHECK_CREATE, data: check });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "createCheck")); next(handleError(error, SERVICE_NAME, "createCheck"));
} }
}; };
const getChecks = async (req, res, next) => { const getChecks = async (req, res, next) => {
try { try {
await getChecksParamValidation.validateAsync(req.params); await getChecksParamValidation.validateAsync(req.params);
await getChecksQueryValidation.validateAsync(req.query); await getChecksQueryValidation.validateAsync(req.query);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const checks = await req.db.getChecks(req); const checks = await req.db.getChecks(req);
const checksCount = await req.db.getChecksCount(req); const checksCount = await req.db.getChecksCount(req);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.CHECK_GET, msg: successMessages.CHECK_GET,
data: { checksCount, checks }, data: { checksCount, checks },
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getChecks")); next(handleError(error, SERVICE_NAME, "getChecks"));
} }
}; };
const getTeamChecks = async (req, res, next) => { const getTeamChecks = async (req, res, next) => {
try { try {
await getTeamChecksParamValidation.validateAsync(req.params); await getTeamChecksParamValidation.validateAsync(req.params);
await getTeamChecksQueryValidation.validateAsync(req.query); await getTeamChecksQueryValidation.validateAsync(req.query);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const checkData = await req.db.getTeamChecks(req); const checkData = await req.db.getTeamChecks(req);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.CHECK_GET, msg: successMessages.CHECK_GET,
data: checkData, data: checkData,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getTeamChecks")); next(handleError(error, SERVICE_NAME, "getTeamChecks"));
} }
}; };
const deleteChecks = async (req, res, next) => { const deleteChecks = async (req, res, next) => {
try { try {
await deleteChecksParamValidation.validateAsync(req.params); await deleteChecksParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const deletedCount = await req.db.deleteChecks(req.params.monitorId); const deletedCount = await req.db.deleteChecks(req.params.monitorId);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.CHECK_DELETE, msg: successMessages.CHECK_DELETE,
data: { deletedCount }, data: { deletedCount },
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "deleteChecks")); next(handleError(error, SERVICE_NAME, "deleteChecks"));
} }
}; };
const deleteChecksByTeamId = async (req, res, next) => { const deleteChecksByTeamId = async (req, res, next) => {
try { try {
await deleteChecksByTeamIdParamValidation.validateAsync(req.params); await deleteChecksByTeamIdParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const deletedCount = await req.db.deleteChecksByTeamId(req.params.teamId); const deletedCount = await req.db.deleteChecksByTeamId(req.params.teamId);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.CHECK_DELETE, msg: successMessages.CHECK_DELETE,
data: { deletedCount }, data: { deletedCount },
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "deleteChecksByTeamId")); next(handleError(error, SERVICE_NAME, "deleteChecksByTeamId"));
} }
}; };
const updateChecksTTL = async (req, res, next) => { const updateChecksTTL = async (req, res, next) => {
const SECONDS_PER_DAY = 86400; const SECONDS_PER_DAY = 86400;
try { try {
await updateChecksTTLBodyValidation.validateAsync(req.body); await updateChecksTTLBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
// Get user's teamId // Get user's teamId
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = req.settingsService.getSettings();
const { teamId } = jwt.verify(token, jwtSecret); const { teamId } = jwt.verify(token, jwtSecret);
const ttl = parseInt(req.body.ttl, 10) * SECONDS_PER_DAY; const ttl = parseInt(req.body.ttl, 10) * SECONDS_PER_DAY;
await req.db.updateChecksTTL(teamId, ttl); await req.db.updateChecksTTL(teamId, ttl);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.CHECK_UPDATE_TTL, msg: successMessages.CHECK_UPDATE_TTL,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "updateTTL")); next(handleError(error, SERVICE_NAME, "updateTTL"));
} }
}; };
export { export {
createCheck, createCheck,
getChecks, getChecks,
getTeamChecks, getTeamChecks,
deleteChecks, deleteChecks,
deleteChecksByTeamId, deleteChecksByTeamId,
updateChecksTTL, updateChecksTTL,
}; };
+49 -53
View File
@@ -1,7 +1,7 @@
import { import {
inviteRoleValidation, inviteRoleValidation,
inviteBodyValidation, inviteBodyValidation,
inviteVerificationBodyValidation, inviteVerificationBodyValidation,
} from "../validation/joi.js"; } from "../validation/joi.js";
import logger from "../utils/logger.js"; import logger from "../utils/logger.js";
import dotenv from "dotenv"; import dotenv from "dotenv";
@@ -27,62 +27,58 @@ const SERVICE_NAME = "inviteController";
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const issueInvitation = async (req, res, next) => { const issueInvitation = async (req, res, next) => {
try { try {
// Only admins can invite // Only admins can invite
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const { role, firstname, teamId } = jwt.decode(token); const { role, firstname, teamId } = jwt.decode(token);
req.body.teamId = teamId; req.body.teamId = teamId;
try { try {
await inviteRoleValidation.validateAsync({ roles: role }); await inviteRoleValidation.validateAsync({ roles: role });
await inviteBodyValidation.validateAsync(req.body); await inviteBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
const inviteToken = await req.db.requestInviteToken({ ...req.body }); const inviteToken = await req.db.requestInviteToken({ ...req.body });
const { clientHost } = req.settingsService.getSettings(); const { clientHost } = req.settingsService.getSettings();
req.emailService req.emailService
.buildAndSendEmail( .buildAndSendEmail(
"employeeActivationTemplate", "employeeActivationTemplate",
{ {
name: firstname, name: firstname,
link: `${clientHost}/register/${inviteToken.token}`, link: `${clientHost}/register/${inviteToken.token}`,
}, },
req.body.email, req.body.email,
"Welcome to Uptime Monitor" "Welcome to Uptime Monitor"
) )
.catch((error) => { .catch((error) => {
logger.error("Error sending invite email", { logger.error("Error sending invite email", {
service: SERVICE_NAME, service: SERVICE_NAME,
error: error.message, error: error.message,
}); });
}); });
return res return res.status(200).json({ success: true, msg: "Invite sent", data: inviteToken });
.status(200) } catch (error) {
.json({ success: true, msg: "Invite sent", data: inviteToken }); next(handleError(error, SERVICE_NAME, "inviteController"));
} catch (error) { }
next(handleError(error, SERVICE_NAME, "inviteController"));
}
}; };
const inviteVerifyController = async (req, res, next) => { const inviteVerifyController = async (req, res, next) => {
try { try {
await inviteVerificationBodyValidation.validateAsync(req.body); await inviteVerificationBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const invite = await req.db.getInviteToken(req.body.token); const invite = await req.db.getInviteToken(req.body.token);
res res.status(200).json({ status: "success", msg: "Invite verified", data: invite });
.status(200) } catch (error) {
.json({ status: "success", msg: "Invite verified", data: invite }); next(handleError(error, SERVICE_NAME, "inviteVerifyController"));
} catch (error) { }
next(handleError(error, SERVICE_NAME, "inviteVerifyController"));
}
}; };
export { issueInvitation, inviteVerifyController }; export { issueInvitation, inviteVerifyController };
+134 -138
View File
@@ -1,11 +1,11 @@
import { import {
createMaintenanceWindowBodyValidation, createMaintenanceWindowBodyValidation,
editMaintenanceWindowByIdParamValidation, editMaintenanceWindowByIdParamValidation,
editMaintenanceByIdWindowBodyValidation, editMaintenanceByIdWindowBodyValidation,
getMaintenanceWindowByIdParamValidation, getMaintenanceWindowByIdParamValidation,
getMaintenanceWindowsByMonitorIdParamValidation, getMaintenanceWindowsByMonitorIdParamValidation,
getMaintenanceWindowsByTeamIdQueryValidation, getMaintenanceWindowsByTeamIdQueryValidation,
deleteMaintenanceWindowByIdParamValidation, deleteMaintenanceWindowByIdParamValidation,
} from "../validation/joi.js"; } from "../validation/joi.js";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import { getTokenFromHeaders } from "../utils/utils.js"; import { getTokenFromHeaders } from "../utils/utils.js";
@@ -15,157 +15,153 @@ import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "maintenanceWindowController"; const SERVICE_NAME = "maintenanceWindowController";
const createMaintenanceWindows = async (req, res, next) => { const createMaintenanceWindows = async (req, res, next) => {
try { try {
await createMaintenanceWindowBodyValidation.validateAsync(req.body); await createMaintenanceWindowBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = req.settingsService.getSettings();
const { teamId } = jwt.verify(token, jwtSecret); const { teamId } = jwt.verify(token, jwtSecret);
const monitorIds = req.body.monitors; const monitorIds = req.body.monitors;
const dbTransactions = monitorIds.map((monitorId) => { const dbTransactions = monitorIds.map((monitorId) => {
return req.db.createMaintenanceWindow({ return req.db.createMaintenanceWindow({
teamId, teamId,
monitorId, monitorId,
name: req.body.name, name: req.body.name,
active: req.body.active ? req.body.active : true, active: req.body.active ? req.body.active : true,
repeat: req.body.repeat, repeat: req.body.repeat,
start: req.body.start, start: req.body.start,
end: req.body.end, end: req.body.end,
}); });
}); });
await Promise.all(dbTransactions); await Promise.all(dbTransactions);
return res.status(201).json({ return res.status(201).json({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_CREATE, msg: successMessages.MAINTENANCE_WINDOW_CREATE,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "createMaintenanceWindow")); next(handleError(error, SERVICE_NAME, "createMaintenanceWindow"));
} }
}; };
const getMaintenanceWindowById = async (req, res, next) => { const getMaintenanceWindowById = async (req, res, next) => {
try { try {
await getMaintenanceWindowByIdParamValidation.validateAsync(req.params); await getMaintenanceWindowByIdParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const maintenanceWindow = await req.db.getMaintenanceWindowById( const maintenanceWindow = await req.db.getMaintenanceWindowById(req.params.id);
req.params.id return res.status(200).json({
); success: true,
return res.status(200).json({ msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID,
success: true, data: maintenanceWindow,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID, });
data: maintenanceWindow, } catch (error) {
}); next(handleError(error, SERVICE_NAME, "getMaintenanceWindowById"));
} catch (error) { }
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowById"));
}
}; };
const getMaintenanceWindowsByTeamId = async (req, res, next) => { const getMaintenanceWindowsByTeamId = async (req, res, next) => {
try { try {
await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query); await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = req.settingsService.getSettings();
const { teamId } = jwt.verify(token, jwtSecret); const { teamId } = jwt.verify(token, jwtSecret);
const maintenanceWindows = await req.db.getMaintenanceWindowsByTeamId( const maintenanceWindows = await req.db.getMaintenanceWindowsByTeamId(
teamId, teamId,
req.query req.query
); );
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM, msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM,
data: maintenanceWindows, data: maintenanceWindows,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByUserId")); next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByUserId"));
} }
}; };
const getMaintenanceWindowsByMonitorId = async (req, res, next) => { const getMaintenanceWindowsByMonitorId = async (req, res, next) => {
try { try {
await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync( await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync(req.params);
req.params } catch (error) {
); next(handleValidationError(error, SERVICE_NAME));
} catch (error) { return;
next(handleValidationError(error, SERVICE_NAME)); }
return;
}
try { try {
const maintenanceWindows = await req.db.getMaintenanceWindowsByMonitorId( const maintenanceWindows = await req.db.getMaintenanceWindowsByMonitorId(
req.params.monitorId req.params.monitorId
); );
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_USER, msg: successMessages.MAINTENANCE_WINDOW_GET_BY_USER,
data: maintenanceWindows, data: maintenanceWindows,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByMonitorId")); next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByMonitorId"));
} }
}; };
const deleteMaintenanceWindow = async (req, res, next) => { const deleteMaintenanceWindow = async (req, res, next) => {
try { try {
await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params); await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
await req.db.deleteMaintenanceWindowById(req.params.id); await req.db.deleteMaintenanceWindowById(req.params.id);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_DELETE, msg: successMessages.MAINTENANCE_WINDOW_DELETE,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "deleteMaintenanceWindow")); next(handleError(error, SERVICE_NAME, "deleteMaintenanceWindow"));
} }
}; };
const editMaintenanceWindow = async (req, res, next) => { const editMaintenanceWindow = async (req, res, next) => {
try { try {
await editMaintenanceWindowByIdParamValidation.validateAsync(req.params); await editMaintenanceWindowByIdParamValidation.validateAsync(req.params);
await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body); await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const editedMaintenanceWindow = await req.db.editMaintenanceWindowById( const editedMaintenanceWindow = await req.db.editMaintenanceWindowById(
req.params.id, req.params.id,
req.body req.body
); );
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_EDIT, msg: successMessages.MAINTENANCE_WINDOW_EDIT,
data: editedMaintenanceWindow, data: editedMaintenanceWindow,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "editMaintenanceWindow")); next(handleError(error, SERVICE_NAME, "editMaintenanceWindow"));
} }
}; };
export { export {
createMaintenanceWindows, createMaintenanceWindows,
getMaintenanceWindowById, getMaintenanceWindowById,
getMaintenanceWindowsByTeamId, getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId, getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindow, deleteMaintenanceWindow,
editMaintenanceWindow, editMaintenanceWindow,
}; };
+39 -41
View File
@@ -4,56 +4,54 @@ import { errorMessages, successMessages } from "../utils/messages.js";
const SERVICE_NAME = "JobQueueController"; const SERVICE_NAME = "JobQueueController";
const getMetrics = async (req, res, next) => { const getMetrics = async (req, res, next) => {
try { try {
const metrics = await req.jobQueue.getMetrics(); const metrics = await req.jobQueue.getMetrics();
res.status(200).json({ res.status(200).json({
success: true, success: true,
msg: successMessages.QUEUE_GET_METRICS, msg: successMessages.QUEUE_GET_METRICS,
data: metrics, data: metrics,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getMetrics")); next(handleError(error, SERVICE_NAME, "getMetrics"));
return; return;
} }
}; };
const getJobs = async (req, res, next) => { const getJobs = async (req, res, next) => {
try { try {
const jobs = await req.jobQueue.getJobStats(); const jobs = await req.jobQueue.getJobStats();
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.QUEUE_GET_METRICS, msg: successMessages.QUEUE_GET_METRICS,
data: jobs, data: jobs,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getJobs")); next(handleError(error, SERVICE_NAME, "getJobs"));
return; return;
} }
}; };
const addJob = async (req, res, next) => { const addJob = async (req, res, next) => {
try { try {
await req.jobQueue.addJob(Math.random().toString(36).substring(7)); await req.jobQueue.addJob(Math.random().toString(36).substring(7));
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.QUEUE_ADD_JOB, msg: successMessages.QUEUE_ADD_JOB,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "addJob")); next(handleError(error, SERVICE_NAME, "addJob"));
return; return;
} }
}; };
const obliterateQueue = async (req, res, next) => { const obliterateQueue = async (req, res, next) => {
try { try {
await req.jobQueue.obliterate(); await req.jobQueue.obliterate();
return res return res.status(200).json({ success: true, msg: successMessages.QUEUE_OBLITERATE });
.status(200) } catch (error) {
.json({ success: true, msg: successMessages.QUEUE_OBLITERATE }); next(handleError(error, SERVICE_NAME, "obliterateQueue"));
} catch (error) { return;
next(handleError(error, SERVICE_NAME, "obliterateQueue")); }
return;
}
}; };
export { getMetrics, getJobs, addJob, obliterateQueue }; export { getMetrics, getJobs, addJob, obliterateQueue };
+29 -29
View File
@@ -4,39 +4,39 @@ import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "SettingsController"; const SERVICE_NAME = "SettingsController";
const getAppSettings = async (req, res, next) => { const getAppSettings = async (req, res, next) => {
try { try {
const settings = { ...(await req.settingsService.getSettings()) }; const settings = { ...(await req.settingsService.getSettings()) };
delete settings.jwtSecret; delete settings.jwtSecret;
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.GET_APP_SETTINGS, msg: successMessages.GET_APP_SETTINGS,
data: settings, data: settings,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getAppSettings")); next(handleError(error, SERVICE_NAME, "getAppSettings"));
} }
}; };
const updateAppSettings = async (req, res, next) => { const updateAppSettings = async (req, res, next) => {
try { try {
await updateAppSettingsBodyValidation.validateAsync(req.body); await updateAppSettingsBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
await req.db.updateAppSettings(req.body); await req.db.updateAppSettings(req.body);
const updatedSettings = { ...(await req.settingsService.reloadSettings()) }; const updatedSettings = { ...(await req.settingsService.reloadSettings()) };
delete updatedSettings.jwtSecret; delete updatedSettings.jwtSecret;
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.UPDATE_APP_SETTINGS, msg: successMessages.UPDATE_APP_SETTINGS,
data: updatedSettings, data: updatedSettings,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "updateAppSettings")); next(handleError(error, SERVICE_NAME, "updateAppSettings"));
} }
}; };
export { getAppSettings, updateAppSettings }; export { getAppSettings, updateAppSettings };
+79 -79
View File
@@ -28,111 +28,111 @@ let FAKE_MONITOR_DATA = [];
const USERS = []; const USERS = [];
const connect = async () => { const connect = async () => {
try { try {
await console.log("Connected to FakeDB"); await console.log("Connected to FakeDB");
} catch (error) { } catch (error) {
console.error(error); console.error(error);
} }
}; };
const insertUser = async (req, res) => { const insertUser = async (req, res) => {
try { try {
const newUser = new UserModel({ ...req.body }); const newUser = new UserModel({ ...req.body });
const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait
newUser.password = await bcrypt.hash(newUser.password, salt); // hash is also async, need to eitehr await or use hashSync newUser.password = await bcrypt.hash(newUser.password, salt); // hash is also async, need to eitehr await or use hashSync
USERS.push(newUser); USERS.push(newUser);
const userToReturn = { ...newUser._doc }; const userToReturn = { ...newUser._doc };
delete userToReturn.password; delete userToReturn.password;
return userToReturn; return userToReturn;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };
const getUserByEmail = async (req, res) => { const getUserByEmail = async (req, res) => {
const email = req.body.email; const email = req.body.email;
try { try {
const idx = USERS.findIndex((user) => { const idx = USERS.findIndex((user) => {
return user.email === email; return user.email === email;
}); });
if (idx === -1) { if (idx === -1) {
return null; return null;
} }
return USERS[idx]; return USERS[idx];
} catch (error) { } catch (error) {
throw new Error(`User with email ${email} not found`); throw new Error(`User with email ${email} not found`);
} }
}; };
const getAllMonitors = async () => { const getAllMonitors = async () => {
return FAKE_MONITOR_DATA; return FAKE_MONITOR_DATA;
}; };
const getMonitorById = async (monitorId) => { const getMonitorById = async (monitorId) => {
const idx = FAKE_MONITOR_DATA.findIndex((monitor) => { const idx = FAKE_MONITOR_DATA.findIndex((monitor) => {
return monitor.id === monitorId; return monitor.id === monitorId;
}); });
if (idx === -1) { if (idx === -1) {
throw new Error(`Monitor with id ${monitorId} not found`); throw new Error(`Monitor with id ${monitorId} not found`);
} }
return FAKE_MONITOR_DATA[idx]; return FAKE_MONITOR_DATA[idx];
}; };
const getMonitorsByUserId = async (userId) => { const getMonitorsByUserId = async (userId) => {
const userMonitors = FAKE_MONITOR_DATA.filter((monitor) => { const userMonitors = FAKE_MONITOR_DATA.filter((monitor) => {
return monitor.userId === userId; return monitor.userId === userId;
}); });
if (userMonitors.length === 0) { if (userMonitors.length === 0) {
throw new Error(`Monitors for user ${userId} not found`); throw new Error(`Monitors for user ${userId} not found`);
} }
return userMonitors; return userMonitors;
}; };
const createMonitor = async (req, res) => { const createMonitor = async (req, res) => {
const monitor = new Monitor(req.body); const monitor = new Monitor(req.body);
monitor.createdAt = Date.now(); monitor.createdAt = Date.now();
monitor.updatedAt = Date.now(); monitor.updatedAt = Date.now();
FAKE_MONITOR_DATA.push(monitor); FAKE_MONITOR_DATA.push(monitor);
return monitor; return monitor;
}; };
const deleteMonitor = async (req, res) => { const deleteMonitor = async (req, res) => {
const monitorId = req.params.monitorId; const monitorId = req.params.monitorId;
try { try {
const monitor = getMonitorById(monitorId); const monitor = getMonitorById(monitorId);
FAKE_MONITOR_DATA = FAKE_MONITOR_DATA.filter((monitor) => { FAKE_MONITOR_DATA = FAKE_MONITOR_DATA.filter((monitor) => {
return monitor.id !== monitorId; return monitor.id !== monitorId;
}); });
return monitor; return monitor;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };
const editMonitor = async (req, res) => { const editMonitor = async (req, res) => {
const monitorId = req.params.monitorId; const monitorId = req.params.monitorId;
const idx = FAKE_MONITOR_DATA.findIndex((monitor) => { const idx = FAKE_MONITOR_DATA.findIndex((monitor) => {
return monitor._id.toString() === monitorId; return monitor._id.toString() === monitorId;
}); });
const oldMonitor = FAKE_MONITOR_DATA[idx]; const oldMonitor = FAKE_MONITOR_DATA[idx];
const editedMonitor = new Monitor({ ...req.body }); const editedMonitor = new Monitor({ ...req.body });
editedMonitor._id = oldMonitor._id; editedMonitor._id = oldMonitor._id;
editedMonitor.userId = oldMonitor.userId; editedMonitor.userId = oldMonitor.userId;
editedMonitor.updatedAt = Date.now(); editedMonitor.updatedAt = Date.now();
editedMonitor.createdAt = oldMonitor.createdAt; editedMonitor.createdAt = oldMonitor.createdAt;
FAKE_MONITOR_DATA[idx] = editedMonitor; FAKE_MONITOR_DATA[idx] = editedMonitor;
return FAKE_MONITOR_DATA[idx]; return FAKE_MONITOR_DATA[idx];
}; };
module.exports = { module.exports = {
connect, connect,
insertUser, insertUser,
getUserByEmail, getUserByEmail,
getAllMonitors, getAllMonitors,
getMonitorById, getMonitorById,
getMonitorsByUserId, getMonitorsByUserId,
createMonitor, createMonitor,
deleteMonitor, deleteMonitor,
editMonitor, editMonitor,
}; };
+85 -85
View File
@@ -1,91 +1,91 @@
import mongoose from "mongoose"; import mongoose from "mongoose";
const AppSettingsSchema = mongoose.Schema( const AppSettingsSchema = mongoose.Schema(
{ {
apiBaseUrl: { apiBaseUrl: {
type: String, type: String,
required: true, required: true,
default: "http://localhost:5000/api/v1", default: "http://localhost:5000/api/v1",
}, },
logLevel: { logLevel: {
type: String, type: String,
default: "debug", default: "debug",
enum: ["debug", "none", "error", "warn"], enum: ["debug", "none", "error", "warn"],
}, },
clientHost: { clientHost: {
type: String, type: String,
required: true, required: true,
default: "http://localhost:5173", default: "http://localhost:5173",
}, },
jwtSecret: { jwtSecret: {
type: String, type: String,
required: true, required: true,
default: "my_secret", default: "my_secret",
}, },
refreshTokenSecret: { refreshTokenSecret: {
type: String, type: String,
required: true, required: true,
default: "my_refresh_secret", default: "my_refresh_secret",
}, },
dbType: { dbType: {
type: String, type: String,
required: true, required: true,
default: "MongoDB", default: "MongoDB",
}, },
dbConnectionString: { dbConnectionString: {
type: String, type: String,
required: true, required: true,
default: "mongodb://localhost:27017/uptime_db", default: "mongodb://localhost:27017/uptime_db",
}, },
redisHost: { redisHost: {
type: String, type: String,
required: true, required: true,
default: "127.0.0.1", default: "127.0.0.1",
}, },
redisPort: { redisPort: {
type: Number, type: Number,
default: "6379", default: "6379",
}, },
jwtTTL: { jwtTTL: {
type: String, type: String,
required: true, required: true,
default: "2h", default: "2h",
}, },
refreshTokenTTL: { refreshTokenTTL: {
type: String, type: String,
required: true, required: true,
default: "7d", default: "7d",
}, },
pagespeedApiKey: { pagespeedApiKey: {
type: String, type: String,
default: "", default: "",
}, },
systemEmailHost: { systemEmailHost: {
type: String, type: String,
default: "smtp.gmail.com", default: "smtp.gmail.com",
}, },
systemEmailPort: { systemEmailPort: {
type: Number, type: Number,
default: 465, default: 465,
}, },
systemEmailAddress: { systemEmailAddress: {
type: String, type: String,
default: "", default: "",
}, },
systemEmailPassword: { systemEmailPassword: {
type: String, type: String,
default: "", default: "",
}, },
singleton: { singleton: {
type: Boolean, type: Boolean,
required: true, required: true,
unique: true, unique: true,
default: true, default: true,
}, },
}, },
{ {
timestamps: true, timestamps: true,
} }
); );
export default mongoose.model("AppSettings", AppSettingsSchema); export default mongoose.model("AppSettings", AppSettingsSchema);
+60 -60
View File
@@ -9,67 +9,67 @@ import Notification from "./Notification.js";
* about the status and response of a particular check event. * about the status and response of a particular check event.
*/ */
const CheckSchema = mongoose.Schema( const CheckSchema = mongoose.Schema(
{ {
/** /**
* Reference to the associated Monitor document. * Reference to the associated Monitor document.
* *
* @type {mongoose.Schema.Types.ObjectId} * @type {mongoose.Schema.Types.ObjectId}
*/ */
monitorId: { monitorId: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
ref: "Monitor", ref: "Monitor",
immutable: true, immutable: true,
index: true, index: true,
}, },
/** /**
* Status of the check (true for up, false for down). * Status of the check (true for up, false for down).
* *
* @type {Boolean} * @type {Boolean}
*/ */
status: { status: {
type: Boolean, type: Boolean,
index: true, index: true,
}, },
/** /**
* Response time of the check in milliseconds. * Response time of the check in milliseconds.
* *
* @type {Number} * @type {Number}
*/ */
responseTime: { responseTime: {
type: Number, type: Number,
}, },
/** /**
* HTTP status code received during the check. * HTTP status code received during the check.
* *
* @type {Number} * @type {Number}
*/ */
statusCode: { statusCode: {
type: Number, type: Number,
index: true, index: true,
}, },
/** /**
* Message or description of the check result. * Message or description of the check result.
* *
* @type {String} * @type {String}
*/ */
message: { message: {
type: String, type: String,
}, },
/** /**
* Expiry date of the check, auto-calculated to expire after 30 days. * Expiry date of the check, auto-calculated to expire after 30 days.
* *
* @type {Date} * @type {Date}
*/ */
expiry: { expiry: {
type: Date, type: Date,
default: Date.now, default: Date.now,
expires: 60 * 60 * 24 * 30, // 30 days expires: 60 * 60 * 24 * 30, // 30 days
}, },
}, },
{ {
timestamps: true, // Adds createdAt and updatedAt timestamps timestamps: true, // Adds createdAt and updatedAt timestamps
} }
); );
CheckSchema.index({ createdAt: 1 }); CheckSchema.index({ createdAt: 1 });
+29 -29
View File
@@ -1,34 +1,34 @@
import mongoose from "mongoose"; import mongoose from "mongoose";
const InviteTokenSchema = mongoose.Schema( const InviteTokenSchema = mongoose.Schema(
{ {
email: { email: {
type: String, type: String,
required: true, required: true,
unique: true, unique: true,
}, },
teamId: { teamId: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
ref: "Team", ref: "Team",
immutable: true, immutable: true,
required: true, required: true,
}, },
role: { role: {
type: Array, type: Array,
required: true, required: true,
}, },
token: { token: {
type: String, type: String,
required: true, required: true,
}, },
expiry: { expiry: {
type: Date, type: Date,
default: Date.now, default: Date.now,
expires: 3600, expires: 3600,
}, },
}, },
{ {
timestamps: true, timestamps: true,
} }
); );
export default mongoose.model("InviteToken", InviteTokenSchema); export default mongoose.model("InviteToken", InviteTokenSchema);
+35 -35
View File
@@ -27,42 +27,42 @@ import mongoose from "mongoose";
*/ */
const MaintenanceWindow = mongoose.Schema( const MaintenanceWindow = mongoose.Schema(
{ {
monitorId: { monitorId: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
ref: "Monitor", ref: "Monitor",
immutable: true, immutable: true,
}, },
teamId: { teamId: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
ref: "Team", ref: "Team",
immutable: true, immutable: true,
}, },
active: { active: {
type: Boolean, type: Boolean,
default: true, default: true,
}, },
name: { name: {
type: String, type: String,
}, },
repeat: { repeat: {
type: Number, type: Number,
}, },
start: { start: {
type: Date, type: Date,
}, },
end: { end: {
type: Date, type: Date,
}, },
expiry: { expiry: {
type: Date, type: Date,
index: { expires: "0s" }, index: { expires: "0s" },
}, },
}, },
{ {
timestamps: true, timestamps: true,
} }
); );
export default mongoose.model("MaintenanceWindow", MaintenanceWindow); export default mongoose.model("MaintenanceWindow", MaintenanceWindow);
+56 -56
View File
@@ -2,62 +2,62 @@ import mongoose from "mongoose";
import Notification from "./Notification.js"; import Notification from "./Notification.js";
const MonitorSchema = mongoose.Schema( const MonitorSchema = mongoose.Schema(
{ {
userId: { userId: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
ref: "User", ref: "User",
immutable: true, immutable: true,
required: true, required: true,
}, },
teamId: { teamId: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
ref: "Team", ref: "Team",
immutable: true, immutable: true,
required: true, required: true,
}, },
name: { name: {
type: String, type: String,
required: true, required: true,
}, },
description: { description: {
type: String, type: String,
}, },
status: { status: {
type: Boolean, type: Boolean,
default: undefined, default: undefined,
}, },
type: { type: {
type: String, type: String,
required: true, required: true,
enum: ["http", "ping", "pagespeed"], enum: ["http", "ping", "pagespeed"],
}, },
url: { url: {
type: String, type: String,
required: true, required: true,
}, },
isActive: { isActive: {
type: Boolean, type: Boolean,
default: true, default: true,
}, },
interval: { interval: {
// in milliseconds // in milliseconds
type: Number, type: Number,
default: 60000, default: 60000,
}, },
uptimePercentage: { uptimePercentage: {
type: Number, type: Number,
default: undefined, default: undefined,
}, },
notifications: [ notifications: [
{ {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
ref: "Notification", ref: "Notification",
}, },
], ],
}, },
{ {
timestamps: true, timestamps: true,
} }
); );
export default mongoose.model("Monitor", MonitorSchema); export default mongoose.model("Monitor", MonitorSchema);
+20 -20
View File
@@ -1,24 +1,24 @@
import mongoose from "mongoose"; import mongoose from "mongoose";
const NotificationSchema = mongoose.Schema( const NotificationSchema = mongoose.Schema(
{ {
monitorId: { monitorId: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
ref: "Monitor", ref: "Monitor",
immutable: true, immutable: true,
}, },
type: { type: {
type: String, type: String,
enum: ["email", "sms"], enum: ["email", "sms"],
}, },
address: { address: {
type: String, type: String,
}, },
phone: { phone: {
type: String, type: String,
}, },
}, },
{ {
timestamps: true, timestamps: true,
} }
); );
export default mongoose.model("Notification", NotificationSchema); export default mongoose.model("Notification", NotificationSchema);
+81 -81
View File
@@ -1,36 +1,36 @@
import mongoose from "mongoose"; import mongoose from "mongoose";
const AuditSchema = mongoose.Schema({ const AuditSchema = mongoose.Schema({
id: { type: String, required: true }, id: { type: String, required: true },
title: { type: String, required: true }, title: { type: String, required: true },
description: { type: String, required: true }, description: { type: String, required: true },
score: { type: Number, required: true }, score: { type: Number, required: true },
scoreDisplayMode: { type: String, required: true }, scoreDisplayMode: { type: String, required: true },
displayValue: { type: String, required: true }, displayValue: { type: String, required: true },
numericValue: { type: Number, required: true }, numericValue: { type: Number, required: true },
numericUnit: { type: String, required: true }, numericUnit: { type: String, required: true },
}); });
const AuditsSchema = mongoose.Schema({ const AuditsSchema = mongoose.Schema({
cls: { cls: {
type: AuditSchema, type: AuditSchema,
required: true, required: true,
}, },
si: { si: {
type: AuditSchema, type: AuditSchema,
required: true, required: true,
}, },
fcp: { fcp: {
type: AuditSchema, type: AuditSchema,
required: true, required: true,
}, },
lcp: { lcp: {
type: AuditSchema, type: AuditSchema,
required: true, required: true,
}, },
tbt: { tbt: {
type: AuditSchema, type: AuditSchema,
required: true, required: true,
}, },
}); });
/** /**
@@ -44,40 +44,40 @@ const AuditsSchema = mongoose.Schema({
*/ */
const PageSpeedCheck = mongoose.Schema( const PageSpeedCheck = mongoose.Schema(
{ {
monitorId: { monitorId: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
ref: "Monitor", ref: "Monitor",
immutable: true, immutable: true,
}, },
status: { status: {
type: Boolean, type: Boolean,
required: true, required: true,
}, },
accessibility: { accessibility: {
type: Number, type: Number,
required: true, required: true,
}, },
bestPractices: { bestPractices: {
type: Number, type: Number,
required: true, required: true,
}, },
seo: { seo: {
type: Number, type: Number,
required: true, required: true,
}, },
performance: { performance: {
type: Number, type: Number,
required: true, required: true,
}, },
audits: { audits: {
type: AuditsSchema, type: AuditsSchema,
required: true, required: true,
}, },
}, },
{ {
timestamps: true, timestamps: true,
} }
); );
/** /**
@@ -86,26 +86,26 @@ const PageSpeedCheck = mongoose.Schema(
*/ */
PageSpeedCheck.pre("save", async function (next) { PageSpeedCheck.pre("save", async function (next) {
try { try {
const monitor = await mongoose.model("Monitor").findById(this.monitorId); const monitor = await mongoose.model("Monitor").findById(this.monitorId);
if (monitor && monitor.status !== this.status) { if (monitor && monitor.status !== this.status) {
if (monitor.status === true && this.status === false) { if (monitor.status === true && this.status === false) {
// TODO issue alert // TODO issue alert
console.log("Monitor went down"); console.log("Monitor went down");
} }
if (monitor.status === false && this.status === true) { if (monitor.status === false && this.status === true) {
// TODO issue alert // TODO issue alert
console.log("Monitor went up"); console.log("Monitor went up");
} }
monitor.status = this.status; monitor.status = this.status;
await monitor.save(); await monitor.save();
} }
} catch (error) { } catch (error) {
console.log(error); console.log(error);
} finally { } finally {
next(); next();
} }
}); });
export default mongoose.model("PageSpeedCheck", PageSpeedCheck); export default mongoose.model("PageSpeedCheck", PageSpeedCheck);
+19 -19
View File
@@ -1,25 +1,25 @@
import mongoose from "mongoose"; import mongoose from "mongoose";
const RecoveryTokenSchema = mongoose.Schema( const RecoveryTokenSchema = mongoose.Schema(
{ {
email: { email: {
type: String, type: String,
required: true, required: true,
unique: true, unique: true,
}, },
token: { token: {
type: String, type: String,
required: true, required: true,
}, },
expiry: { expiry: {
type: Date, type: Date,
default: Date.now, default: Date.now,
expires: 600, expires: 600,
}, },
}, },
{ {
timestamps: true, timestamps: true,
} }
); );
export default mongoose.model("RecoveryToken", RecoveryTokenSchema); export default mongoose.model("RecoveryToken", RecoveryTokenSchema);
+10 -10
View File
@@ -1,14 +1,14 @@
import mongoose from "mongoose"; import mongoose from "mongoose";
const TeamSchema = mongoose.Schema( const TeamSchema = mongoose.Schema(
{ {
email: { email: {
type: String, type: String,
required: true, required: true,
unique: true, unique: true,
}, },
}, },
{ {
timestamps: true, timestamps: true,
} }
); );
export default mongoose.model("Team", TeamSchema); export default mongoose.model("Team", TeamSchema);
+120 -120
View File
@@ -7,34 +7,34 @@ import AppSettings from "../models/AppSettings.js";
//**************************************** //****************************************
const connect = async () => { const connect = async () => {
try { try {
const connectionString = const connectionString =
process.env.DB_CONNECTION_STRING || "mongodb://localhost:27017/uptime_db"; process.env.DB_CONNECTION_STRING || "mongodb://localhost:27017/uptime_db";
await mongoose.connect(connectionString); await mongoose.connect(connectionString);
// If there are no AppSettings, create one // If there are no AppSettings, create one
let appSettings = await AppSettings.find(); let appSettings = await AppSettings.find();
if (appSettings.length === 0) { if (appSettings.length === 0) {
appSettings = new AppSettings({}); appSettings = new AppSettings({});
await appSettings.save(); await appSettings.save();
} }
console.log("Connected to MongoDB"); console.log("Connected to MongoDB");
} catch (error) { } catch (error) {
console.error("Failed to connect to MongoDB"); console.error("Failed to connect to MongoDB");
throw error; throw error;
} }
}; };
const checkSuperadmin = async (req, res) => { const checkSuperadmin = async (req, res) => {
try { try {
const superAdmin = await UserModel.findOne({ role: "superadmin" }); const superAdmin = await UserModel.findOne({ role: "superadmin" });
if (superAdmin !== null) { if (superAdmin !== null) {
return true; return true;
} }
return false; return false;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };
//**************************************** //****************************************
@@ -42,14 +42,14 @@ const checkSuperadmin = async (req, res) => {
//**************************************** //****************************************
import { import {
insertUser, insertUser,
getUserByEmail, getUserByEmail,
updateUser, updateUser,
deleteUser, deleteUser,
deleteTeam, deleteTeam,
deleteAllOtherUsers, deleteAllOtherUsers,
getAllUsers, getAllUsers,
logoutUser, logoutUser,
} from "./modules/userModule.js"; } from "./modules/userModule.js";
//**************************************** //****************************************
@@ -57,18 +57,18 @@ import {
//**************************************** //****************************************
import { import {
requestInviteToken, requestInviteToken,
getInviteToken, getInviteToken,
getInviteTokenAndDelete, getInviteTokenAndDelete,
} from "./modules/inviteModule.js"; } from "./modules/inviteModule.js";
//**************************************** //****************************************
// Recovery Operations // Recovery Operations
//**************************************** //****************************************
import { import {
requestRecoveryToken, requestRecoveryToken,
validateRecoveryToken, validateRecoveryToken,
resetPassword, resetPassword,
} from "./modules/recoveryModule.js"; } from "./modules/recoveryModule.js";
//**************************************** //****************************************
@@ -76,17 +76,17 @@ import {
//**************************************** //****************************************
import { import {
getAllMonitors, getAllMonitors,
getMonitorStatsById, getMonitorStatsById,
getMonitorById, getMonitorById,
getMonitorsAndSummaryByTeamId, getMonitorsAndSummaryByTeamId,
getMonitorsByTeamId, getMonitorsByTeamId,
createMonitor, createMonitor,
deleteMonitor, deleteMonitor,
deleteAllMonitors, deleteAllMonitors,
deleteMonitorsByUserId, deleteMonitorsByUserId,
editMonitor, editMonitor,
addDemoMonitors, addDemoMonitors,
} from "./modules/monitorModule.js"; } from "./modules/monitorModule.js";
//**************************************** //****************************************
@@ -94,9 +94,9 @@ import {
//**************************************** //****************************************
import { import {
createPageSpeedCheck, createPageSpeedCheck,
getPageSpeedChecks, getPageSpeedChecks,
deletePageSpeedChecksByMonitorId, deletePageSpeedChecksByMonitorId,
} from "./modules/pageSpeedCheckModule.js"; } from "./modules/pageSpeedCheckModule.js";
//**************************************** //****************************************
@@ -104,36 +104,36 @@ import {
//**************************************** //****************************************
import { import {
createCheck, createCheck,
getChecksCount, getChecksCount,
getChecks, getChecks,
getTeamChecks, getTeamChecks,
deleteChecks, deleteChecks,
deleteChecksByTeamId, deleteChecksByTeamId,
updateChecksTTL, updateChecksTTL,
} from "./modules/checkModule.js"; } from "./modules/checkModule.js";
//**************************************** //****************************************
// Maintenance Window // Maintenance Window
//**************************************** //****************************************
import { import {
createMaintenanceWindow, createMaintenanceWindow,
getMaintenanceWindowById, getMaintenanceWindowById,
getMaintenanceWindowsByTeamId, getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId, getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindowById, deleteMaintenanceWindowById,
deleteMaintenanceWindowByMonitorId, deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId, deleteMaintenanceWindowByUserId,
editMaintenanceWindowById, editMaintenanceWindowById,
} from "./modules/maintenanceWindowModule.js"; } from "./modules/maintenanceWindowModule.js";
//**************************************** //****************************************
// Notifications // Notifications
//**************************************** //****************************************
import { import {
createNotification, createNotification,
getNotificationsByMonitorId, getNotificationsByMonitorId,
deleteNotificationsByMonitorId, deleteNotificationsByMonitorId,
} from "./modules/notificationModule.js"; } from "./modules/notificationModule.js";
//**************************************** //****************************************
@@ -142,54 +142,54 @@ import {
import { getAppSettings, updateAppSettings } from "./modules/settingsModule.js"; import { getAppSettings, updateAppSettings } from "./modules/settingsModule.js";
export default { export default {
connect, connect,
insertUser, insertUser,
getUserByEmail, getUserByEmail,
updateUser, updateUser,
deleteUser, deleteUser,
deleteTeam, deleteTeam,
deleteAllOtherUsers, deleteAllOtherUsers,
getAllUsers, getAllUsers,
logoutUser, logoutUser,
requestInviteToken, requestInviteToken,
getInviteToken, getInviteToken,
getInviteTokenAndDelete, getInviteTokenAndDelete,
requestRecoveryToken, requestRecoveryToken,
validateRecoveryToken, validateRecoveryToken,
resetPassword, resetPassword,
checkSuperadmin, checkSuperadmin,
getAllMonitors, getAllMonitors,
getMonitorStatsById, getMonitorStatsById,
getMonitorById, getMonitorById,
getMonitorsAndSummaryByTeamId, getMonitorsAndSummaryByTeamId,
getMonitorsByTeamId, getMonitorsByTeamId,
createMonitor, createMonitor,
deleteMonitor, deleteMonitor,
deleteAllMonitors, deleteAllMonitors,
editMonitor, editMonitor,
addDemoMonitors, addDemoMonitors,
createCheck, createCheck,
getChecksCount, getChecksCount,
getChecks, getChecks,
getTeamChecks, getTeamChecks,
deleteChecks, deleteChecks,
deleteChecksByTeamId, deleteChecksByTeamId,
updateChecksTTL, updateChecksTTL,
deleteMonitorsByUserId, deleteMonitorsByUserId,
createPageSpeedCheck, createPageSpeedCheck,
getPageSpeedChecks, getPageSpeedChecks,
deletePageSpeedChecksByMonitorId, deletePageSpeedChecksByMonitorId,
createMaintenanceWindow, createMaintenanceWindow,
getMaintenanceWindowsByTeamId, getMaintenanceWindowsByTeamId,
getMaintenanceWindowById, getMaintenanceWindowById,
getMaintenanceWindowsByMonitorId, getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindowById, deleteMaintenanceWindowById,
deleteMaintenanceWindowByMonitorId, deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId, deleteMaintenanceWindowByUserId,
editMaintenanceWindowById, editMaintenanceWindowById,
createNotification, createNotification,
getNotificationsByMonitorId, getNotificationsByMonitorId,
deleteNotificationsByMonitorId, deleteNotificationsByMonitorId,
getAppSettings, getAppSettings,
updateAppSettings, updateAppSettings,
}; };
+197 -197
View File
@@ -4,9 +4,9 @@ import User from "../../models/User.js";
import logger from "../../../utils/logger.js"; import logger from "../../../utils/logger.js";
const SERVICE_NAME = "checkModule"; const SERVICE_NAME = "checkModule";
const dateRangeLookup = { const dateRangeLookup = {
day: new Date(new Date().setDate(new Date().getDate() - 1)), day: new Date(new Date().setDate(new Date().getDate() - 1)),
week: new Date(new Date().setDate(new Date().getDate() - 7)), week: new Date(new Date().setDate(new Date().getDate() - 7)),
month: new Date(new Date().setMonth(new Date().getMonth() - 1)), month: new Date(new Date().setMonth(new Date().getMonth() - 1)),
}; };
/** /**
@@ -23,67 +23,67 @@ const dateRangeLookup = {
*/ */
const createCheck = async (checkData) => { const createCheck = async (checkData) => {
try { try {
const { monitorId, status } = checkData; const { monitorId, status } = checkData;
const n = (await Check.countDocuments({ monitorId })) + 1; const n = (await Check.countDocuments({ monitorId })) + 1;
const check = await new Check({ ...checkData }).save(); const check = await new Check({ ...checkData }).save();
const monitor = await Monitor.findById(monitorId); const monitor = await Monitor.findById(monitorId);
if (!monitor) { if (!monitor) {
logger.error("Monitor not found", { logger.error("Monitor not found", {
service: SERVICE_NAME, service: SERVICE_NAME,
monitorId, monitorId,
}); });
return; return;
} }
// Update uptime percentage // Update uptime percentage
if (monitor.uptimePercentage === undefined) { if (monitor.uptimePercentage === undefined) {
monitor.uptimePercentage = status === true ? 1 : 0; monitor.uptimePercentage = status === true ? 1 : 0;
} else { } else {
monitor.uptimePercentage = monitor.uptimePercentage =
(monitor.uptimePercentage * (n - 1) + (status === true ? 1 : 0)) / n; (monitor.uptimePercentage * (n - 1) + (status === true ? 1 : 0)) / n;
} }
await monitor.save(); await monitor.save();
return check; return check;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "createCheck"; error.method = "createCheck";
throw error; throw error;
} }
}; };
const getChecksCount = async (req) => { const getChecksCount = async (req) => {
const monitorId = req.params.monitorId; const monitorId = req.params.monitorId;
const dateRange = req.query.dateRange; const dateRange = req.query.dateRange;
const filter = req.query.filter; const filter = req.query.filter;
// Build query // Build query
const checksQuery = { monitorId: monitorId }; const checksQuery = { monitorId: monitorId };
// Filter checks by "day", "week", or "month" // Filter checks by "day", "week", or "month"
if (dateRange !== undefined) { if (dateRange !== undefined) {
checksQuery.createdAt = { $gte: dateRangeLookup[dateRange] }; checksQuery.createdAt = { $gte: dateRangeLookup[dateRange] };
} }
if (filter !== undefined) { if (filter !== undefined) {
checksQuery.status = false; checksQuery.status = false;
switch (filter) { switch (filter) {
case "all": case "all":
break; break;
case "down": case "down":
break; break;
case "resolve": case "resolve":
checksQuery.statusCode = 5000; checksQuery.statusCode = 5000;
break; break;
default: default:
console.log("default"); console.log("default");
break; break;
} }
} }
const count = await Check.countDocuments(checksQuery); const count = await Check.countDocuments(checksQuery);
return count; return count;
}; };
/** /**
@@ -95,104 +95,104 @@ const getChecksCount = async (req) => {
*/ */
const getChecks = async (req) => { const getChecks = async (req) => {
try { try {
const { monitorId } = req.params; const { monitorId } = req.params;
let { sortOrder, limit, dateRange, filter, page, rowsPerPage } = req.query; let { sortOrder, limit, dateRange, filter, page, rowsPerPage } = req.query;
// Default limit to 0 if not provided // Default limit to 0 if not provided
limit = limit === "undefined" ? 0 : limit; limit = limit === "undefined" ? 0 : limit;
// Default sort order is newest -> oldest // Default sort order is newest -> oldest
sortOrder = sortOrder === "asc" ? 1 : -1; sortOrder = sortOrder === "asc" ? 1 : -1;
// Build query // Build query
const checksQuery = { monitorId: monitorId }; const checksQuery = { monitorId: monitorId };
// Filter checks by "day", "week", or "month" // Filter checks by "day", "week", or "month"
if (dateRange !== undefined) { if (dateRange !== undefined) {
checksQuery.createdAt = { $gte: dateRangeLookup[dateRange] }; checksQuery.createdAt = { $gte: dateRangeLookup[dateRange] };
} }
// Fitler checks by status // Fitler checks by status
if (filter !== undefined) { if (filter !== undefined) {
checksQuery.status = false; checksQuery.status = false;
switch (filter) { switch (filter) {
case "all": case "all":
break; break;
case "down": case "down":
break; break;
case "resolve": case "resolve":
checksQuery.statusCode = 5000; checksQuery.statusCode = 5000;
break; break;
default: default:
console.log("default"); console.log("default");
break; break;
} }
} }
// Need to skip and limit here // Need to skip and limit here
let skip = 0; let skip = 0;
if (page && rowsPerPage) { if (page && rowsPerPage) {
skip = page * rowsPerPage; skip = page * rowsPerPage;
} }
const checks = await Check.find(checksQuery) const checks = await Check.find(checksQuery)
.skip(skip) .skip(skip)
.limit(rowsPerPage) .limit(rowsPerPage)
.sort({ createdAt: sortOrder }); .sort({ createdAt: sortOrder });
return checks; return checks;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getChecks"; error.method = "getChecks";
throw error; throw error;
} }
}; };
const getTeamChecks = async (req) => { const getTeamChecks = async (req) => {
const { teamId } = req.params; const { teamId } = req.params;
let { sortOrder, limit, dateRange, filter, page, rowsPerPage } = req.query; let { sortOrder, limit, dateRange, filter, page, rowsPerPage } = req.query;
// Get monitorIDs // Get monitorIDs
const userMonitors = await Monitor.find({ teamId: teamId }).select("_id"); const userMonitors = await Monitor.find({ teamId: teamId }).select("_id");
//Build check query //Build check query
// Default limit to 0 if not provided // Default limit to 0 if not provided
limit = limit === undefined ? 0 : limit; limit = limit === undefined ? 0 : limit;
// Default sort order is newest -> oldest // Default sort order is newest -> oldest
sortOrder = sortOrder === "asc" ? 1 : -1; sortOrder = sortOrder === "asc" ? 1 : -1;
checksQuery = { monitorId: { $in: userMonitors } }; checksQuery = { monitorId: { $in: userMonitors } };
if (filter !== undefined) { if (filter !== undefined) {
checksQuery.status = false; checksQuery.status = false;
switch (filter) { switch (filter) {
case "all": case "all":
break; break;
case "down": case "down":
break; break;
case "resolve": case "resolve":
checksQuery.statusCode = 5000; checksQuery.statusCode = 5000;
break; break;
default: default:
console.log("default"); console.log("default");
break; break;
} }
} }
if (dateRange !== undefined) { if (dateRange !== undefined) {
checksQuery.createdAt = { $gte: dateRangeLookup[dateRange] }; checksQuery.createdAt = { $gte: dateRangeLookup[dateRange] };
} }
// Skip and limit for pagination // Skip and limit for pagination
let skip = 0; let skip = 0;
if (page && rowsPerPage) { if (page && rowsPerPage) {
skip = page * rowsPerPage; skip = page * rowsPerPage;
} }
const checksCount = await Check.countDocuments(checksQuery); const checksCount = await Check.countDocuments(checksQuery);
const checks = await Check.find(checksQuery) const checks = await Check.find(checksQuery)
.skip(skip) .skip(skip)
.limit(rowsPerPage) .limit(rowsPerPage)
.sort({ createdAt: sortOrder }) .sort({ createdAt: sortOrder })
.select(["monitorId", "status", "responseTime", "statusCode", "message"]); .select(["monitorId", "status", "responseTime", "statusCode", "message"]);
return { checksCount, checks }; return { checksCount, checks };
}; };
/** /**
@@ -204,14 +204,14 @@ const getTeamChecks = async (req) => {
*/ */
const deleteChecks = async (monitorId) => { const deleteChecks = async (monitorId) => {
try { try {
const result = await Check.deleteMany({ monitorId }); const result = await Check.deleteMany({ monitorId });
return result.deletedCount; return result.deletedCount;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteChecks"; error.method = "deleteChecks";
throw error; throw error;
} }
}; };
/** /**
@@ -223,63 +223,63 @@ const deleteChecks = async (monitorId) => {
*/ */
const deleteChecksByTeamId = async (teamId) => { const deleteChecksByTeamId = async (teamId) => {
try { try {
const teamMonitors = await Monitor.find({ teamId: teamId }); const teamMonitors = await Monitor.find({ teamId: teamId });
let totalDeletedCount = 0; let totalDeletedCount = 0;
await Promise.all( await Promise.all(
teamMonitors.map(async (monitor) => { teamMonitors.map(async (monitor) => {
const result = await Check.deleteMany({ monitorId: monitor._id }); const result = await Check.deleteMany({ monitorId: monitor._id });
totalDeletedCount += result.deletedCount; totalDeletedCount += result.deletedCount;
monitor.status = true; monitor.status = true;
await monitor.save(); await monitor.save();
}) })
); );
return totalDeletedCount; return totalDeletedCount;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteChecksByTeamId"; error.method = "deleteChecksByTeamId";
throw error; throw error;
} }
}; };
const updateChecksTTL = async (teamId, ttl) => { const updateChecksTTL = async (teamId, ttl) => {
try { try {
await Check.collection.dropIndex("expiry_1"); await Check.collection.dropIndex("expiry_1");
} catch (error) { } catch (error) {
logger.error("Failed to drop index", { logger.error("Failed to drop index", {
service: SERVICE_NAME, service: SERVICE_NAME,
method: "updateChecksTTL", method: "updateChecksTTL",
}); });
} }
try { try {
await Check.collection.createIndex( await Check.collection.createIndex(
{ expiry: 1 }, { expiry: 1 },
{ expireAfterSeconds: ttl } // TTL in seconds, adjust as necessary { expireAfterSeconds: ttl } // TTL in seconds, adjust as necessary
); );
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "updateChecksTTL"; error.method = "updateChecksTTL";
throw error; throw error;
} }
// Update user // Update user
try { try {
await User.updateMany({ teamId: teamId }, { checkTTL: ttl }); await User.updateMany({ teamId: teamId }, { checkTTL: ttl });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "updateChecksTTL"; error.method = "updateChecksTTL";
throw error; throw error;
} }
}; };
export { export {
createCheck, createCheck,
getChecksCount, getChecksCount,
getChecks, getChecks,
getTeamChecks, getTeamChecks,
deleteChecks, deleteChecks,
deleteChecksByTeamId, deleteChecksByTeamId,
updateChecksTTL, updateChecksTTL,
}; };
+37 -37
View File
@@ -18,17 +18,17 @@ const SERVICE_NAME = "inviteModule";
* @throws {Error} If there is an error. * @throws {Error} If there is an error.
*/ */
const requestInviteToken = async (userData) => { const requestInviteToken = async (userData) => {
try { try {
await InviteToken.deleteMany({ email: userData.email }); await InviteToken.deleteMany({ email: userData.email });
userData.token = crypto.randomBytes(32).toString("hex"); userData.token = crypto.randomBytes(32).toString("hex");
let inviteToken = new InviteToken(userData); let inviteToken = new InviteToken(userData);
await inviteToken.save(); await inviteToken.save();
return inviteToken; return inviteToken;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "requestInviteToken"; error.method = "requestInviteToken";
throw error; throw error;
} }
}; };
/** /**
@@ -42,19 +42,19 @@ const requestInviteToken = async (userData) => {
* @throws {Error} If the invite token is not found or there is another error. * @throws {Error} If the invite token is not found or there is another error.
*/ */
const getInviteToken = async (token) => { const getInviteToken = async (token) => {
try { try {
const invite = await InviteToken.findOne({ const invite = await InviteToken.findOne({
token, token,
}); });
if (invite === null) { if (invite === null) {
throw new Error(errorMessages.AUTH_INVITE_NOT_FOUND); throw new Error(errorMessages.AUTH_INVITE_NOT_FOUND);
} }
return invite; return invite;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getInviteToken"; error.method = "getInviteToken";
throw error; throw error;
} }
}; };
/** /**
@@ -68,19 +68,19 @@ const getInviteToken = async (token) => {
* @throws {Error} If the invite token is not found or there is another error. * @throws {Error} If the invite token is not found or there is another error.
*/ */
const getInviteTokenAndDelete = async (token) => { const getInviteTokenAndDelete = async (token) => {
try { try {
const invite = await InviteToken.findOneAndDelete({ const invite = await InviteToken.findOneAndDelete({
token, token,
}); });
if (invite === null) { if (invite === null) {
throw new Error(errorMessages.AUTH_INVITE_NOT_FOUND); throw new Error(errorMessages.AUTH_INVITE_NOT_FOUND);
} }
return invite; return invite;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getInviteToken"; error.method = "getInviteToken";
throw error; throw error;
} }
}; };
export { requestInviteToken, getInviteToken, getInviteTokenAndDelete }; export { requestInviteToken, getInviteToken, getInviteTokenAndDelete };
+108 -111
View File
@@ -27,35 +27,35 @@ const SERVICE_NAME = "maintenanceWindowModule";
* .catch(error => console.error(error)); * .catch(error => console.error(error));
*/ */
const createMaintenanceWindow = async (maintenanceWindowData) => { const createMaintenanceWindow = async (maintenanceWindowData) => {
try { try {
const maintenanceWindow = new MaintenanceWindow({ const maintenanceWindow = new MaintenanceWindow({
...maintenanceWindowData, ...maintenanceWindowData,
}); });
// If the maintenance window is a one time window, set the expiry to the end date // If the maintenance window is a one time window, set the expiry to the end date
if (maintenanceWindowData.oneTime) { if (maintenanceWindowData.oneTime) {
maintenanceWindow.expiry = maintenanceWindowData.end; maintenanceWindow.expiry = maintenanceWindowData.end;
} }
const result = await maintenanceWindow.save(); const result = await maintenanceWindow.save();
return result; return result;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "createMaintenanceWindow"; error.method = "createMaintenanceWindow";
throw error; throw error;
} }
}; };
const getMaintenanceWindowById = async (maintenanceWindowId) => { const getMaintenanceWindowById = async (maintenanceWindowId) => {
try { try {
const maintenanceWindow = await MaintenanceWindow.findById({ const maintenanceWindow = await MaintenanceWindow.findById({
_id: maintenanceWindowId, _id: maintenanceWindowId,
}); });
return maintenanceWindow; return maintenanceWindow;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowById"; error.method = "getMaintenanceWindowById";
throw error; throw error;
} }
}; };
/** /**
@@ -72,38 +72,38 @@ const getMaintenanceWindowById = async (maintenanceWindowId) => {
* .catch(error => console.error(error)); * .catch(error => console.error(error));
*/ */
const getMaintenanceWindowsByTeamId = async (teamId, query) => { const getMaintenanceWindowsByTeamId = async (teamId, query) => {
try { try {
let { active, page, rowsPerPage, field, order } = query || {}; let { active, page, rowsPerPage, field, order } = query || {};
const maintenanceQuery = { teamId }; const maintenanceQuery = { teamId };
if (active !== undefined) maintenanceQuery.active = active; if (active !== undefined) maintenanceQuery.active = active;
const maintenanceWindowCount = const maintenanceWindowCount =
await MaintenanceWindow.countDocuments(maintenanceQuery); await MaintenanceWindow.countDocuments(maintenanceQuery);
// Pagination // Pagination
let skip = 0; let skip = 0;
if (page && rowsPerPage) { if (page && rowsPerPage) {
skip = page * rowsPerPage; skip = page * rowsPerPage;
} }
// Sorting // Sorting
let sort = {}; let sort = {};
if (field !== undefined && order !== undefined) { if (field !== undefined && order !== undefined) {
sort[field] = order === "asc" ? 1 : -1; sort[field] = order === "asc" ? 1 : -1;
} }
const maintenanceWindows = await MaintenanceWindow.find(maintenanceQuery) const maintenanceWindows = await MaintenanceWindow.find(maintenanceQuery)
.skip(skip) .skip(skip)
.limit(rowsPerPage) .limit(rowsPerPage)
.sort(sort); .sort(sort);
return { maintenanceWindows, maintenanceWindowCount }; return { maintenanceWindows, maintenanceWindowCount };
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowByUserId"; error.method = "getMaintenanceWindowByUserId";
throw error; throw error;
} }
}; };
/** /**
@@ -119,16 +119,16 @@ const getMaintenanceWindowsByTeamId = async (teamId, query) => {
* .catch(error => console.error(error)); * .catch(error => console.error(error));
*/ */
const getMaintenanceWindowsByMonitorId = async (monitorId) => { const getMaintenanceWindowsByMonitorId = async (monitorId) => {
try { try {
const maintenanceWindows = await MaintenanceWindow.find({ const maintenanceWindows = await MaintenanceWindow.find({
monitorId: monitorId, monitorId: monitorId,
}); });
return maintenanceWindows; return maintenanceWindows;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowsByMonitorId"; error.method = "getMaintenanceWindowsByMonitorId";
throw error; throw error;
} }
}; };
/** /**
@@ -144,15 +144,15 @@ const getMaintenanceWindowsByMonitorId = async (monitorId) => {
* .catch(error => console.error(error)); * .catch(error => console.error(error));
*/ */
const deleteMaintenanceWindowById = async (maintenanceWindowId) => { const deleteMaintenanceWindowById = async (maintenanceWindowId) => {
try { try {
const maintenanceWindow = const maintenanceWindow =
await MaintenanceWindow.findByIdAndDelete(maintenanceWindowId); await MaintenanceWindow.findByIdAndDelete(maintenanceWindowId);
return maintenanceWindow; return maintenanceWindow;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteMaintenanceWindowById"; error.method = "deleteMaintenanceWindowById";
throw error; throw error;
} }
}; };
/** /**
@@ -168,14 +168,14 @@ const deleteMaintenanceWindowById = async (maintenanceWindowId) => {
* .catch(error => console.error(error)); * .catch(error => console.error(error));
*/ */
const deleteMaintenanceWindowByMonitorId = async (monitorId) => { const deleteMaintenanceWindowByMonitorId = async (monitorId) => {
try { try {
const result = await MaintenanceWindow.deleteMany({ monitorId: monitorId }); const result = await MaintenanceWindow.deleteMany({ monitorId: monitorId });
return result; return result;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteMaintenanceWindowByMonitorId"; error.method = "deleteMaintenanceWindowByMonitorId";
throw error; throw error;
} }
}; };
/** /**
@@ -191,42 +191,39 @@ const deleteMaintenanceWindowByMonitorId = async (monitorId) => {
* .catch(error => console.error(error)); * .catch(error => console.error(error));
*/ */
const deleteMaintenanceWindowByUserId = async (userId) => { const deleteMaintenanceWindowByUserId = async (userId) => {
try { try {
const result = await MaintenanceWindow.deleteMany({ userId: userId }); const result = await MaintenanceWindow.deleteMany({ userId: userId });
return result; return result;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteMaintenanceWindowByUserId"; error.method = "deleteMaintenanceWindowByUserId";
throw error; throw error;
} }
}; };
const editMaintenanceWindowById = async ( const editMaintenanceWindowById = async (maintenanceWindowId, maintenanceWindowData) => {
maintenanceWindowId, console.log(maintenanceWindowData);
maintenanceWindowData try {
) => { const editedMaintenanceWindow = MaintenanceWindow.findByIdAndUpdate(
console.log(maintenanceWindowData); maintenanceWindowId,
try { maintenanceWindowData,
const editedMaintenanceWindow = MaintenanceWindow.findByIdAndUpdate( { new: true }
maintenanceWindowId, );
maintenanceWindowData, return editedMaintenanceWindow;
{ new: true } } catch (error) {
); error.service = SERVICE_NAME;
return editedMaintenanceWindow; error.method = "editMaintenanceWindowById";
} catch (error) { throw error;
error.service = SERVICE_NAME; }
error.method = "editMaintenanceWindowById";
throw error;
}
}; };
export { export {
createMaintenanceWindow, createMaintenanceWindow,
getMaintenanceWindowById, getMaintenanceWindowById,
getMaintenanceWindowsByTeamId, getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId, getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindowById, deleteMaintenanceWindowById,
deleteMaintenanceWindowByMonitorId, deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId, deleteMaintenanceWindowByUserId,
editMaintenanceWindowById, editMaintenanceWindowById,
}; };
+375 -386
View File
@@ -11,10 +11,7 @@ import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); const __dirname = path.dirname(__filename);
const demoMonitorsPath = path.resolve( const demoMonitorsPath = path.resolve(__dirname, "../../../utils/demoMonitors.json");
__dirname,
"../../../utils/demoMonitors.json"
);
const demoMonitors = JSON.parse(fs.readFileSync(demoMonitorsPath, "utf8")); const demoMonitors = JSON.parse(fs.readFileSync(demoMonitorsPath, "utf8"));
const SERVICE_NAME = "monitorModule"; const SERVICE_NAME = "monitorModule";
@@ -28,14 +25,14 @@ const SERVICE_NAME = "monitorModule";
* @throws {Error} * @throws {Error}
*/ */
const getAllMonitors = async (req, res) => { const getAllMonitors = async (req, res) => {
try { try {
const monitors = await Monitor.find(); const monitors = await Monitor.find();
return monitors; return monitors;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getAllMonitors"; error.method = "getAllMonitors";
throw error; throw error;
} }
}; };
/** /**
@@ -44,27 +41,27 @@ const getAllMonitors = async (req, res) => {
* @returns {number} Uptime duration in ms. * @returns {number} Uptime duration in ms.
*/ */
const calculateUptimeDuration = (checks) => { const calculateUptimeDuration = (checks) => {
if (!checks || checks.length === 0) { if (!checks || checks.length === 0) {
return 0; return 0;
} }
const latestCheck = new Date(checks[0].createdAt); const latestCheck = new Date(checks[0].createdAt);
let latestDownCheck = 0; let latestDownCheck = 0;
for (let i = checks.length; i <= 0; i--) { for (let i = checks.length; i <= 0; i--) {
if (checks[i].status === false) { if (checks[i].status === false) {
latestDownCheck = new Date(checks[i].createdAt); latestDownCheck = new Date(checks[i].createdAt);
break; break;
} }
} }
// If no down check is found, uptime is from the last check to now // If no down check is found, uptime is from the last check to now
if (latestDownCheck === 0) { if (latestDownCheck === 0) {
return Date.now() - new Date(checks[checks.length - 1].createdAt); return Date.now() - new Date(checks[checks.length - 1].createdAt);
} }
// Otherwise the uptime is from the last check to the last down check // Otherwise the uptime is from the last check to the last down check
return latestCheck - latestDownCheck; return latestCheck - latestDownCheck;
}; };
/** /**
@@ -73,11 +70,11 @@ const calculateUptimeDuration = (checks) => {
* @returns {number} Timestamp of the most recent check. * @returns {number} Timestamp of the most recent check.
*/ */
const getLastChecked = (checks) => { const getLastChecked = (checks) => {
if (!checks || checks.length === 0) { if (!checks || checks.length === 0) {
return 0; // Handle case when no checks are available return 0; // Handle case when no checks are available
} }
// Data is sorted newest->oldest, so last check is the most recent // Data is sorted newest->oldest, so last check is the most recent
return new Date() - new Date(checks[0].createdAt); return new Date() - new Date(checks[0].createdAt);
}; };
/** /**
@@ -86,10 +83,10 @@ const getLastChecked = (checks) => {
* @returns {number} Timestamp of the most recent check. * @returns {number} Timestamp of the most recent check.
*/ */
const getLatestResponseTime = (checks) => { const getLatestResponseTime = (checks) => {
if (!checks || checks.length === 0) { if (!checks || checks.length === 0) {
return 0; return 0;
} }
return checks[0].responseTime; return checks[0].responseTime;
}; };
/** /**
@@ -98,13 +95,13 @@ const getLatestResponseTime = (checks) => {
* @returns {number} Timestamp of the most recent check. * @returns {number} Timestamp of the most recent check.
*/ */
const getAverageResponseTime = (checks) => { const getAverageResponseTime = (checks) => {
if (!checks || checks.length === 0) { if (!checks || checks.length === 0) {
return 0; return 0;
} }
const aggResponseTime = checks.reduce((sum, check) => { const aggResponseTime = checks.reduce((sum, check) => {
return sum + check.responseTime; return sum + check.responseTime;
}, 0); }, 0);
return aggResponseTime / checks.length; return aggResponseTime / checks.length;
}; };
/** /**
@@ -114,13 +111,13 @@ const getAverageResponseTime = (checks) => {
*/ */
const getUptimePercentage = (checks) => { const getUptimePercentage = (checks) => {
if (!checks || checks.length === 0) { if (!checks || checks.length === 0) {
return 0; return 0;
} }
const upCount = checks.reduce((count, check) => { const upCount = checks.reduce((count, check) => {
return check.status === true ? count + 1 : count; return check.status === true ? count + 1 : count;
}, 0); }, 0);
return (upCount / checks.length) * 100; return (upCount / checks.length) * 100;
}; };
/** /**
@@ -130,12 +127,12 @@ const getUptimePercentage = (checks) => {
*/ */
const getIncidents = (checks) => { const getIncidents = (checks) => {
if (!checks || checks.length === 0) { if (!checks || checks.length === 0) {
return 0; // Handle case when no checks are available return 0; // Handle case when no checks are available
} }
return checks.reduce((acc, check) => { return checks.reduce((acc, check) => {
return check.status === false ? (acc += 1) : acc; return check.status === false ? (acc += 1) : acc;
}, 0); }, 0);
}; };
/** /**
@@ -147,140 +144,136 @@ const getIncidents = (checks) => {
* @throws {Error} * @throws {Error}
*/ */
const getMonitorStatsById = async (req) => { const getMonitorStatsById = async (req) => {
const startDates = { const startDates = {
day: new Date(new Date().setDate(new Date().getDate() - 1)), day: new Date(new Date().setDate(new Date().getDate() - 1)),
week: new Date(new Date().setDate(new Date().getDate() - 7)), week: new Date(new Date().setDate(new Date().getDate() - 7)),
month: new Date(new Date().setMonth(new Date().getMonth() - 1)), month: new Date(new Date().setMonth(new Date().getMonth() - 1)),
}; };
const endDate = new Date(); const endDate = new Date();
try { try {
// Get monitor // Get monitor
const { monitorId } = req.params; const { monitorId } = req.params;
let { limit, sortOrder, dateRange, numToDisplay, normalize } = req.query; let { limit, sortOrder, dateRange, numToDisplay, normalize } = req.query;
const monitor = await Monitor.findById(monitorId); const monitor = await Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) { if (monitor === null || monitor === undefined) {
throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)); throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId));
} }
// This effectively removes limit, returning all checks // This effectively removes limit, returning all checks
if (limit === undefined) limit = 0; if (limit === undefined) limit = 0;
// Default sort order is newest -> oldest // Default sort order is newest -> oldest
sortOrder = sortOrder === "asc" ? 1 : -1; sortOrder = sortOrder === "asc" ? 1 : -1;
let model = let model =
monitor.type === "http" || monitor.type === "ping" monitor.type === "http" || monitor.type === "ping" ? Check : PageSpeedCheck;
? Check
: PageSpeedCheck;
const monitorStats = { const monitorStats = {
...monitor.toObject(), ...monitor.toObject(),
}; };
// Build checks query // Build checks query
const checksQuery = { monitorId: monitor._id }; const checksQuery = { monitorId: monitor._id };
// Get all checks // Get all checks
const checksAll = await model.find(checksQuery).sort({ const checksAll = await model.find(checksQuery).sort({
createdAt: sortOrder, createdAt: sortOrder,
}); });
const checksQueryForDateRange = { const checksQueryForDateRange = {
...checksQuery, ...checksQuery,
createdAt: { createdAt: {
$gte: startDates[dateRange], $gte: startDates[dateRange],
$lte: endDate, $lte: endDate,
}, },
}; };
const checksForDateRange = await model const checksForDateRange = await model
.find(checksQueryForDateRange) .find(checksQueryForDateRange)
.sort({ createdAt: sortOrder }); .sort({ createdAt: sortOrder });
if (monitor.type === "http" || monitor.type === "ping") { if (monitor.type === "http" || monitor.type === "ping") {
// HTTP/PING Specific stats // HTTP/PING Specific stats
monitorStats.periodAvgResponseTime = monitorStats.periodAvgResponseTime = getAverageResponseTime(checksForDateRange);
getAverageResponseTime(checksForDateRange); monitorStats.periodUptime = getUptimePercentage(checksForDateRange);
monitorStats.periodUptime = getUptimePercentage(checksForDateRange);
// Aggregate data // Aggregate data
let groupedChecks; let groupedChecks;
// Group checks by hour if range is day // Group checks by hour if range is day
if (dateRange === "day") { if (dateRange === "day") {
groupedChecks = checksForDateRange.reduce((acc, check) => { groupedChecks = checksForDateRange.reduce((acc, check) => {
const time = new Date(check.createdAt); const time = new Date(check.createdAt);
time.setMinutes(0, 0, 0); time.setMinutes(0, 0, 0);
if (!acc[time]) { if (!acc[time]) {
acc[time] = { time, checks: [] }; acc[time] = { time, checks: [] };
} }
acc[time].checks.push(check); acc[time].checks.push(check);
return acc; return acc;
}, {}); }, {});
} else { } else {
groupedChecks = checksForDateRange.reduce((acc, check) => { groupedChecks = checksForDateRange.reduce((acc, check) => {
const time = new Date(check.createdAt).toISOString().split("T")[0]; // Extract the date part const time = new Date(check.createdAt).toISOString().split("T")[0]; // Extract the date part
if (!acc[time]) { if (!acc[time]) {
acc[time] = { time, checks: [] }; acc[time] = { time, checks: [] };
} }
acc[time].checks.push(check); acc[time].checks.push(check);
return acc; return acc;
}, {}); }, {});
} }
// Map grouped checks to stats // Map grouped checks to stats
const aggregateData = Object.values(groupedChecks).map((group) => { const aggregateData = Object.values(groupedChecks).map((group) => {
const totalChecks = group.checks.length; const totalChecks = group.checks.length;
const uptimePercentage = getUptimePercentage(group.checks); const uptimePercentage = getUptimePercentage(group.checks);
const totalIncidents = group.checks.filter( const totalIncidents = group.checks.filter(
(check) => check.status === false (check) => check.status === false
).length; ).length;
const avgResponseTime = const avgResponseTime =
group.checks.reduce((sum, check) => sum + check.responseTime, 0) / group.checks.reduce((sum, check) => sum + check.responseTime, 0) / totalChecks;
totalChecks;
return { return {
time: group.time, time: group.time,
uptimePercentage, uptimePercentage,
totalChecks, totalChecks,
totalIncidents, totalIncidents,
avgResponseTime, avgResponseTime,
}; };
}); });
monitorStats.aggregateData = aggregateData; monitorStats.aggregateData = aggregateData;
} }
monitorStats.periodIncidents = getIncidents(checksForDateRange); monitorStats.periodIncidents = getIncidents(checksForDateRange);
monitorStats.periodTotalChecks = checksForDateRange.length; monitorStats.periodTotalChecks = checksForDateRange.length;
// If more than numToDisplay checks, pick every nth check // If more than numToDisplay checks, pick every nth check
let nthChecks = checksForDateRange; let nthChecks = checksForDateRange;
if ( if (
numToDisplay !== undefined && numToDisplay !== undefined &&
checksForDateRange && checksForDateRange &&
checksForDateRange.length > numToDisplay checksForDateRange.length > numToDisplay
) { ) {
const n = Math.ceil(checksForDateRange.length / numToDisplay); const n = Math.ceil(checksForDateRange.length / numToDisplay);
nthChecks = checksForDateRange.filter((_, index) => index % n === 0); nthChecks = checksForDateRange.filter((_, index) => index % n === 0);
} }
// Normalize checks if requested // Normalize checks if requested
if (normalize !== undefined) { if (normalize !== undefined) {
const normailzedChecks = NormalizeData(nthChecks, 1, 100); const normailzedChecks = NormalizeData(nthChecks, 1, 100);
monitorStats.checks = normailzedChecks; monitorStats.checks = normailzedChecks;
} else { } else {
monitorStats.checks = nthChecks; monitorStats.checks = nthChecks;
} }
monitorStats.uptimeDuration = calculateUptimeDuration(checksAll); monitorStats.uptimeDuration = calculateUptimeDuration(checksAll);
monitorStats.lastChecked = getLastChecked(checksAll); monitorStats.lastChecked = getLastChecked(checksAll);
monitorStats.latestResponseTime = getLatestResponseTime(checksAll); monitorStats.latestResponseTime = getLatestResponseTime(checksAll);
return monitorStats; return monitorStats;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getMonitorStatsById"; error.method = "getMonitorStatsById";
throw error; throw error;
} }
}; };
/** /**
@@ -292,23 +285,23 @@ const getMonitorStatsById = async (req) => {
* @throws {Error} * @throws {Error}
*/ */
const getMonitorById = async (monitorId) => { const getMonitorById = async (monitorId) => {
try { try {
const monitor = await Monitor.findById(monitorId); const monitor = await Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) { if (monitor === null || monitor === undefined) {
throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)); throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId));
} }
// Get notifications // Get notifications
const notifications = await Notification.find({ const notifications = await Notification.find({
monitorId: monitorId, monitorId: monitorId,
}); });
monitor.notifications = notifications; monitor.notifications = notifications;
const monitorWithNotifications = await monitor.save(); const monitorWithNotifications = await monitor.save();
return monitorWithNotifications; return monitorWithNotifications;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getMonitorById"; error.method = "getMonitorById";
throw error; throw error;
} }
}; };
/** /**
@@ -321,32 +314,32 @@ const getMonitorById = async (monitorId) => {
*/ */
const getMonitorsAndSummaryByTeamId = async (teamId, type) => { const getMonitorsAndSummaryByTeamId = async (teamId, type) => {
try { try {
const monitors = await Monitor.find({ teamId, type }); const monitors = await Monitor.find({ teamId, type });
const monitorCounts = monitors.reduce( const monitorCounts = monitors.reduce(
(acc, monitor) => { (acc, monitor) => {
if (monitor.status === true) { if (monitor.status === true) {
acc.up += 1; acc.up += 1;
} }
if (monitor.status === false) { if (monitor.status === false) {
acc.down += 1; acc.down += 1;
} }
if (monitor.isActive === false) { if (monitor.isActive === false) {
acc.paused += 1; acc.paused += 1;
} }
return acc; return acc;
}, },
{ up: 0, down: 0, paused: 0 } { up: 0, down: 0, paused: 0 }
); );
monitorCounts.total = monitors.length; monitorCounts.total = monitors.length;
return { monitors, monitorCounts }; return { monitors, monitorCounts };
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getMonitorsAndSummaryByTeamId"; error.method = "getMonitorsAndSummaryByTeamId";
throw error; throw error;
} }
}; };
/** /**
@@ -358,104 +351,102 @@ const getMonitorsAndSummaryByTeamId = async (teamId, type) => {
* @throws {Error} * @throws {Error}
*/ */
const getMonitorsByTeamId = async (req, res) => { const getMonitorsByTeamId = async (req, res) => {
try { try {
let { let {
limit, limit,
type, type,
status, status,
checkOrder, checkOrder,
normalize, normalize,
page, page,
rowsPerPage, rowsPerPage,
filter, filter,
field, field,
order, order,
} = req.query || {}; } = req.query || {};
const monitorQuery = { teamId: req.params.teamId }; const monitorQuery = { teamId: req.params.teamId };
if (type !== undefined) { if (type !== undefined) {
monitorQuery.type = type; monitorQuery.type = type;
} }
// Add filter if provided // Add filter if provided
// $options: "i" makes the search case-insensitive // $options: "i" makes the search case-insensitive
if (filter !== undefined) { if (filter !== undefined) {
monitorQuery.$or = [ monitorQuery.$or = [
{ name: { $regex: filter, $options: "i" } }, { name: { $regex: filter, $options: "i" } },
{ url: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } },
]; ];
} }
const monitorsCount = await Monitor.countDocuments(monitorQuery); const monitorsCount = await Monitor.countDocuments(monitorQuery);
// Pagination // Pagination
let skip = 0; let skip = 0;
if (page && rowsPerPage) { if (page && rowsPerPage) {
skip = page * rowsPerPage; skip = page * rowsPerPage;
} }
if (type !== undefined) { if (type !== undefined) {
const types = Array.isArray(type) ? type : [type]; const types = Array.isArray(type) ? type : [type];
monitorQuery.type = { $in: types }; monitorQuery.type = { $in: types };
} }
// Default sort order is newest -> oldest // Default sort order is newest -> oldest
if (checkOrder === "asc") { if (checkOrder === "asc") {
checkOrder = 1; checkOrder = 1;
} else if (checkOrder === "desc") { } else if (checkOrder === "desc") {
checkOrder = -1; checkOrder = -1;
} else checkOrder = -1; } else checkOrder = -1;
// Sort order for monitors // Sort order for monitors
let sort = {}; let sort = {};
if (field !== undefined && order !== undefined) { if (field !== undefined && order !== undefined) {
sort[field] = order === "asc" ? 1 : -1; sort[field] = order === "asc" ? 1 : -1;
} }
const monitors = await Monitor.find(monitorQuery) const monitors = await Monitor.find(monitorQuery)
.skip(skip) .skip(skip)
.limit(rowsPerPage) .limit(rowsPerPage)
.sort(sort); .sort(sort);
// Early return if limit is set to -1, indicating we don't want any checks // Early return if limit is set to -1, indicating we don't want any checks
if (limit === "-1") { if (limit === "-1") {
return { monitors, monitorCount: monitorsCount }; return { monitors, monitorCount: monitorsCount };
} }
// This effectively removes limit, returning all checks // This effectively removes limit, returning all checks
if (limit === undefined) limit = 0; if (limit === undefined) limit = 0;
// Map each monitor to include its associated checks // Map each monitor to include its associated checks
const monitorsWithChecks = await Promise.all( const monitorsWithChecks = await Promise.all(
monitors.map(async (monitor) => { monitors.map(async (monitor) => {
const checksQuery = { monitorId: monitor._id }; const checksQuery = { monitorId: monitor._id };
if (status !== undefined) { if (status !== undefined) {
checksQuery.status = status; checksQuery.status = status;
} }
let model = let model =
monitor.type === "http" || monitor.type === "ping" monitor.type === "http" || monitor.type === "ping" ? Check : PageSpeedCheck;
? Check
: PageSpeedCheck;
// Checks are order newest -> oldest // Checks are order newest -> oldest
let checks = await model let checks = await model
.find(checksQuery) .find(checksQuery)
.sort({ .sort({
createdAt: checkOrder, createdAt: checkOrder,
}) })
.limit(limit); .limit(limit);
//Normalize checks if requested //Normalize checks if requested
if (normalize !== undefined) { if (normalize !== undefined) {
checks = NormalizeData(checks, 10, 100); checks = NormalizeData(checks, 10, 100);
} }
return { ...monitor.toObject(), checks }; return { ...monitor.toObject(), checks };
}) })
); );
return { monitors: monitorsWithChecks, monitorCount: monitorsCount }; return { monitors: monitorsWithChecks, monitorCount: monitorsCount };
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getMonitorsByTeamId"; error.method = "getMonitorsByTeamId";
throw error; throw error;
} }
}; };
/** /**
@@ -467,17 +458,17 @@ const getMonitorsByTeamId = async (req, res) => {
* @throws {Error} * @throws {Error}
*/ */
const createMonitor = async (req, res) => { const createMonitor = async (req, res) => {
try { try {
const monitor = new Monitor({ ...req.body }); const monitor = new Monitor({ ...req.body });
// Remove notifications fom monitor as they aren't needed here // Remove notifications fom monitor as they aren't needed here
monitor.notifications = undefined; monitor.notifications = undefined;
await monitor.save(); await monitor.save();
return monitor; return monitor;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "createMonitor"; error.method = "createMonitor";
throw error; throw error;
} }
}; };
/** /**
@@ -489,18 +480,18 @@ const createMonitor = async (req, res) => {
* @throws {Error} * @throws {Error}
*/ */
const deleteMonitor = async (req, res) => { const deleteMonitor = async (req, res) => {
const monitorId = req.params.monitorId; const monitorId = req.params.monitorId;
try { try {
const monitor = await Monitor.findByIdAndDelete(monitorId); const monitor = await Monitor.findByIdAndDelete(monitorId);
if (!monitor) { if (!monitor) {
throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)); throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId));
} }
return monitor; return monitor;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteMonitor"; error.method = "deleteMonitor";
throw error; throw error;
} }
}; };
/** /**
@@ -508,16 +499,16 @@ const deleteMonitor = async (req, res) => {
*/ */
const deleteAllMonitors = async (teamId) => { const deleteAllMonitors = async (teamId) => {
try { try {
const monitors = await Monitor.find({ teamId }); const monitors = await Monitor.find({ teamId });
const { deletedCount } = await Monitor.deleteMany({ teamId }); const { deletedCount } = await Monitor.deleteMany({ teamId });
return { monitors, deletedCount }; return { monitors, deletedCount };
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteAllMonitors"; error.method = "deleteAllMonitors";
throw error; throw error;
} }
}; };
/** /**
@@ -527,14 +518,14 @@ const deleteAllMonitors = async (teamId) => {
* @returns {Promise} A promise that resolves when the operation is complete. * @returns {Promise} A promise that resolves when the operation is complete.
*/ */
const deleteMonitorsByUserId = async (userId) => { const deleteMonitorsByUserId = async (userId) => {
try { try {
const result = await Monitor.deleteMany({ userId: userId }); const result = await Monitor.deleteMany({ userId: userId });
return result; return result;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteMonitorsByUserId"; error.method = "deleteMonitorsByUserId";
throw error; throw error;
} }
}; };
/** /**
@@ -546,54 +537,52 @@ const deleteMonitorsByUserId = async (userId) => {
* @throws {Error} * @throws {Error}
*/ */
const editMonitor = async (candidateId, candidateMonitor) => { const editMonitor = async (candidateId, candidateMonitor) => {
candidateMonitor.notifications = undefined; candidateMonitor.notifications = undefined;
try { try {
const editedMonitor = await Monitor.findByIdAndUpdate( const editedMonitor = await Monitor.findByIdAndUpdate(candidateId, candidateMonitor, {
candidateId, new: true,
candidateMonitor, });
{ new: true } return editedMonitor;
); } catch (error) {
return editedMonitor; error.service = SERVICE_NAME;
} catch (error) { error.method = "editMonitor";
error.service = SERVICE_NAME; throw error;
error.method = "editMonitor"; }
throw error;
}
}; };
const addDemoMonitors = async (userId, teamId) => { const addDemoMonitors = async (userId, teamId) => {
try { try {
const demoMonitorsToInsert = demoMonitors.map((monitor) => { const demoMonitorsToInsert = demoMonitors.map((monitor) => {
return { return {
userId, userId,
teamId, teamId,
name: monitor.name, name: monitor.name,
description: monitor.name, description: monitor.name,
type: "http", type: "http",
url: monitor.url, url: monitor.url,
interval: 60000, interval: 60000,
}; };
}); });
const insertedMonitors = await Monitor.insertMany(demoMonitorsToInsert); const insertedMonitors = await Monitor.insertMany(demoMonitorsToInsert);
return insertedMonitors; return insertedMonitors;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "addDemoMonitors"; error.method = "addDemoMonitors";
throw error; throw error;
} }
}; };
export { export {
getAllMonitors, getAllMonitors,
getMonitorStatsById, getMonitorStatsById,
getMonitorById, getMonitorById,
getMonitorsAndSummaryByTeamId, getMonitorsAndSummaryByTeamId,
getMonitorsByTeamId, getMonitorsByTeamId,
createMonitor, createMonitor,
deleteMonitor, deleteMonitor,
deleteAllMonitors, deleteAllMonitors,
deleteMonitorsByUserId, deleteMonitorsByUserId,
editMonitor, editMonitor,
addDemoMonitors, addDemoMonitors,
}; };
+27 -27
View File
@@ -11,14 +11,14 @@ const SERVICE_NAME = "notificationModule";
* @throws Will throw an error if the notification cannot be created. * @throws Will throw an error if the notification cannot be created.
*/ */
const createNotification = async (notificationData) => { const createNotification = async (notificationData) => {
try { try {
const notification = await new Notification({ ...notificationData }).save(); const notification = await new Notification({ ...notificationData }).save();
return notification; return notification;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "createNotification"; error.method = "createNotification";
throw error; throw error;
} }
}; };
/** /**
@@ -28,29 +28,29 @@ const createNotification = async (notificationData) => {
* @throws Will throw an error if the notifications cannot be retrieved. * @throws Will throw an error if the notifications cannot be retrieved.
*/ */
const getNotificationsByMonitorId = async (monitorId) => { const getNotificationsByMonitorId = async (monitorId) => {
try { try {
const notifications = await Notification.find({ monitorId }); const notifications = await Notification.find({ monitorId });
return notifications; return notifications;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getNotificationsByMonitorId"; error.method = "getNotificationsByMonitorId";
throw error; throw error;
} }
}; };
const deleteNotificationsByMonitorId = async (monitorId) => { const deleteNotificationsByMonitorId = async (monitorId) => {
try { try {
const result = await Notification.deleteMany({ monitorId }); const result = await Notification.deleteMany({ monitorId });
return result.deletedCount; return result.deletedCount;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteNotificationsByMonitorId"; error.method = "deleteNotificationsByMonitorId";
throw error; throw error;
} }
}; };
export { export {
createNotification, createNotification,
getNotificationsByMonitorId, getNotificationsByMonitorId,
deleteNotificationsByMonitorId, deleteNotificationsByMonitorId,
}; };
+27 -31
View File
@@ -13,16 +13,16 @@ const SERVICE_NAME = "pageSpeedCheckModule";
* @throws {Error} * @throws {Error}
*/ */
const createPageSpeedCheck = async (pageSpeedCheckData) => { const createPageSpeedCheck = async (pageSpeedCheckData) => {
try { try {
const pageSpeedCheck = await new PageSpeedCheck({ const pageSpeedCheck = await new PageSpeedCheck({
...pageSpeedCheckData, ...pageSpeedCheckData,
}).save(); }).save();
return pageSpeedCheck; return pageSpeedCheck;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "createPageSpeedCheck"; error.method = "createPageSpeedCheck";
throw error; throw error;
} }
}; };
/** /**
@@ -34,14 +34,14 @@ const createPageSpeedCheck = async (pageSpeedCheckData) => {
*/ */
const getPageSpeedChecks = async (monitorId) => { const getPageSpeedChecks = async (monitorId) => {
try { try {
const pageSpeedChecks = await PageSpeedCheck.find({ monitorId }); const pageSpeedChecks = await PageSpeedCheck.find({ monitorId });
return pageSpeedChecks; return pageSpeedChecks;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getPageSpeedChecks"; error.method = "getPageSpeedChecks";
throw error; throw error;
} }
}; };
/** /**
@@ -53,18 +53,14 @@ const getPageSpeedChecks = async (monitorId) => {
*/ */
const deletePageSpeedChecksByMonitorId = async (monitorId) => { const deletePageSpeedChecksByMonitorId = async (monitorId) => {
try { try {
const result = await PageSpeedCheck.deleteMany({ monitorId }); const result = await PageSpeedCheck.deleteMany({ monitorId });
return result.deletedCount; return result.deletedCount;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deletePageSpeedChecksByMonitorId"; error.method = "deletePageSpeedChecksByMonitorId";
throw error; throw error;
} }
}; };
export { export { createPageSpeedCheck, getPageSpeedChecks, deletePageSpeedChecksByMonitorId };
createPageSpeedCheck,
getPageSpeedChecks,
deletePageSpeedChecksByMonitorId,
};
+57 -57
View File
@@ -14,72 +14,72 @@ const SERVICE_NAME = "recoveryModule";
* @throws {Error} * @throws {Error}
*/ */
const requestRecoveryToken = async (req, res) => { const requestRecoveryToken = async (req, res) => {
try { try {
// Delete any existing tokens // Delete any existing tokens
await RecoveryToken.deleteMany({ email: req.body.email }); await RecoveryToken.deleteMany({ email: req.body.email });
let recoveryToken = new RecoveryToken({ let recoveryToken = new RecoveryToken({
email: req.body.email, email: req.body.email,
token: crypto.randomBytes(32).toString("hex"), token: crypto.randomBytes(32).toString("hex"),
}); });
await recoveryToken.save(); await recoveryToken.save();
return recoveryToken; return recoveryToken;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "requestRecoveryToken"; error.method = "requestRecoveryToken";
throw error; throw error;
} }
}; };
const validateRecoveryToken = async (req, res) => { const validateRecoveryToken = async (req, res) => {
try { try {
const candidateToken = req.body.recoveryToken; const candidateToken = req.body.recoveryToken;
const recoveryToken = await RecoveryToken.findOne({ const recoveryToken = await RecoveryToken.findOne({
token: candidateToken, token: candidateToken,
}); });
if (recoveryToken !== null) { if (recoveryToken !== null) {
return recoveryToken; return recoveryToken;
} else { } else {
throw new Error(errorMessages.DB_TOKEN_NOT_FOUND); throw new Error(errorMessages.DB_TOKEN_NOT_FOUND);
} }
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "validateRecoveryToken"; error.method = "validateRecoveryToken";
throw error; throw error;
} }
}; };
const resetPassword = async (req, res) => { const resetPassword = async (req, res) => {
try { try {
const newPassword = req.body.password; const newPassword = req.body.password;
// Validate token again // Validate token again
const recoveryToken = await validateRecoveryToken(req, res); const recoveryToken = await validateRecoveryToken(req, res);
const user = await UserModel.findOne({ email: recoveryToken.email }); const user = await UserModel.findOne({ email: recoveryToken.email });
const match = await user.comparePassword(newPassword); const match = await user.comparePassword(newPassword);
if (match === true) { if (match === true) {
throw new Error(errorMessages.DB_RESET_PASSWORD_BAD_MATCH); throw new Error(errorMessages.DB_RESET_PASSWORD_BAD_MATCH);
} }
if (user !== null) { if (user !== null) {
user.password = newPassword; user.password = newPassword;
await user.save(); await user.save();
await RecoveryToken.deleteMany({ email: recoveryToken.email }); await RecoveryToken.deleteMany({ email: recoveryToken.email });
// Fetch the user again without the password // Fetch the user again without the password
const userWithoutPassword = await UserModel.findOne({ const userWithoutPassword = await UserModel.findOne({
email: recoveryToken.email, email: recoveryToken.email,
}) })
.select("-password") .select("-password")
.select("-profileImage"); .select("-profileImage");
return userWithoutPassword; return userWithoutPassword;
} else { } else {
throw new Error(errorMessages.DB_USER_NOT_FOUND); throw new Error(errorMessages.DB_USER_NOT_FOUND);
} }
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "resetPassword"; error.method = "resetPassword";
throw error; throw error;
} }
}; };
export { requestRecoveryToken, validateRecoveryToken, resetPassword }; export { requestRecoveryToken, validateRecoveryToken, resetPassword };
+20 -20
View File
@@ -2,29 +2,29 @@ import AppSettings from "../../models/AppSettings.js";
const SERVICE_NAME = "SettingsModule"; const SERVICE_NAME = "SettingsModule";
const getAppSettings = async () => { const getAppSettings = async () => {
try { try {
const settings = AppSettings.findOne(); const settings = AppSettings.findOne();
return settings; return settings;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getSettings"; error.method = "getSettings";
throw error; throw error;
} }
}; };
const updateAppSettings = async (newSettings) => { const updateAppSettings = async (newSettings) => {
try { try {
const settings = await AppSettings.findOneAndUpdate( const settings = await AppSettings.findOneAndUpdate(
{}, {},
{ $set: newSettings }, { $set: newSettings },
{ new: true } { new: true }
); );
return settings; return settings;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "updateAppSettings"; error.method = "updateAppSettings";
throw error; throw error;
} }
}; };
export { getAppSettings, updateAppSettings }; export { getAppSettings, updateAppSettings };
+131 -135
View File
@@ -16,42 +16,42 @@ const SERVICE_NAME = "userModule";
* @throws {Error} * @throws {Error}
*/ */
const insertUser = async (userData, imageFile) => { const insertUser = async (userData, imageFile) => {
try { try {
if (imageFile) { if (imageFile) {
// 1. Save the full size image // 1. Save the full size image
userData.profileImage = { userData.profileImage = {
data: imageFile.buffer, data: imageFile.buffer,
contentType: imageFile.mimetype, contentType: imageFile.mimetype,
}; };
// 2. Get the avatar sized image // 2. Get the avatar sized image
const avatar = await GenerateAvatarImage(imageFile); const avatar = await GenerateAvatarImage(imageFile);
userData.avatarImage = avatar; userData.avatarImage = avatar;
} }
// Handle creating team if superadmin // Handle creating team if superadmin
if (userData.role.includes("superadmin")) { if (userData.role.includes("superadmin")) {
const team = new TeamModel({ const team = new TeamModel({
email: userData.email, email: userData.email,
}); });
userData.teamId = team._id; userData.teamId = team._id;
userData.checkTTL = 60 * 60 * 24 * 30; userData.checkTTL = 60 * 60 * 24 * 30;
await team.save(); await team.save();
} }
const newUser = new UserModel(userData); const newUser = new UserModel(userData);
await newUser.save(); await newUser.save();
return await UserModel.findOne({ _id: newUser._id }) return await UserModel.findOne({ _id: newUser._id })
.select("-password") .select("-password")
.select("-profileImage"); // .select() doesn't work with create, need to save then find .select("-profileImage"); // .select() doesn't work with create, need to save then find
} catch (error) { } catch (error) {
if (error.code === DUPLICATE_KEY_CODE) { if (error.code === DUPLICATE_KEY_CODE) {
error.message = errorMessages.DB_USER_EXISTS; error.message = errorMessages.DB_USER_EXISTS;
} }
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "insertUser"; error.method = "insertUser";
throw error; throw error;
} }
}; };
/** /**
@@ -66,22 +66,20 @@ const insertUser = async (userData, imageFile) => {
* @throws {Error} * @throws {Error}
*/ */
const getUserByEmail = async (email) => { const getUserByEmail = async (email) => {
try { try {
// Need the password to be able to compare, removed .select() // Need the password to be able to compare, removed .select()
// We can strip the hash before returing the user // We can strip the hash before returing the user
const user = await UserModel.findOne({ email: email }).select( const user = await UserModel.findOne({ email: email }).select("-profileImage");
"-profileImage" if (user) {
); return user;
if (user) { } else {
return user; throw new Error(errorMessages.DB_USER_NOT_FOUND);
} else { }
throw new Error(errorMessages.DB_USER_NOT_FOUND); } catch (error) {
} error.service = SERVICE_NAME;
} catch (error) { error.method = "getUserByEmail";
error.service = SERVICE_NAME; throw error;
error.method = "getUserByEmail"; }
throw error;
}
}; };
/** /**
@@ -94,45 +92,45 @@ const getUserByEmail = async (email) => {
*/ */
const updateUser = async (req, res) => { const updateUser = async (req, res) => {
const candidateUserId = req.params.userId; const candidateUserId = req.params.userId;
try { try {
const candidateUser = { ...req.body }; const candidateUser = { ...req.body };
// ****************************************** // ******************************************
// Handle profile image // Handle profile image
// ****************************************** // ******************************************
if (ParseBoolean(candidateUser.deleteProfileImage) === true) { if (ParseBoolean(candidateUser.deleteProfileImage) === true) {
candidateUser.profileImage = null; candidateUser.profileImage = null;
candidateUser.avatarImage = null; candidateUser.avatarImage = null;
} else if (req.file) { } else if (req.file) {
// 1. Save the full size image // 1. Save the full size image
candidateUser.profileImage = { candidateUser.profileImage = {
data: req.file.buffer, data: req.file.buffer,
contentType: req.file.mimetype, contentType: req.file.mimetype,
}; };
// 2. Get the avaatar sized image // 2. Get the avaatar sized image
const avatar = await GenerateAvatarImage(req.file); const avatar = await GenerateAvatarImage(req.file);
candidateUser.avatarImage = avatar; candidateUser.avatarImage = avatar;
} }
// ****************************************** // ******************************************
// End handling profile image // End handling profile image
// ****************************************** // ******************************************
const updatedUser = await UserModel.findByIdAndUpdate( const updatedUser = await UserModel.findByIdAndUpdate(
candidateUserId, candidateUserId,
candidateUser, candidateUser,
{ new: true } // Returns updated user instead of pre-update user { new: true } // Returns updated user instead of pre-update user
) )
.select("-password") .select("-password")
.select("-profileImage"); .select("-profileImage");
return updatedUser; return updatedUser;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "updateUser"; error.method = "updateUser";
throw error; throw error;
} }
}; };
/** /**
@@ -144,17 +142,17 @@ const updateUser = async (req, res) => {
* @throws {Error} * @throws {Error}
*/ */
const deleteUser = async (userId) => { const deleteUser = async (userId) => {
try { try {
const deletedUser = await UserModel.findByIdAndDelete(userId); const deletedUser = await UserModel.findByIdAndDelete(userId);
if (!deletedUser) { if (!deletedUser) {
throw new Error(errorMessages.DB_USER_NOT_FOUND); throw new Error(errorMessages.DB_USER_NOT_FOUND);
} }
return deletedUser; return deletedUser;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteUser"; error.method = "deleteUser";
throw error; throw error;
} }
}; };
/** /**
@@ -165,56 +163,54 @@ const deleteUser = async (userId) => {
* @throws {Error} * @throws {Error}
*/ */
const deleteTeam = async (teamId) => { const deleteTeam = async (teamId) => {
try { try {
await TeamModel.findByIdAndDelete(teamId); await TeamModel.findByIdAndDelete(teamId);
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteTeam"; error.method = "deleteTeam";
throw error; throw error;
} }
}; };
const deleteAllOtherUsers = async () => { const deleteAllOtherUsers = async () => {
try { try {
await UserModel.deleteMany({ role: { $ne: "superadmin" } }); await UserModel.deleteMany({ role: { $ne: "superadmin" } });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteAllOtherUsers"; error.method = "deleteAllOtherUsers";
throw error; throw error;
} }
}; };
const getAllUsers = async (req, res) => { const getAllUsers = async (req, res) => {
try { try {
const users = await UserModel.find() const users = await UserModel.find().select("-password").select("-profileImage");
.select("-password") return users;
.select("-profileImage"); } catch (error) {
return users; error.service = SERVICE_NAME;
} catch (error) { error.method = "getAllUsers";
error.service = SERVICE_NAME; throw error;
error.method = "getAllUsers"; }
throw error;
}
}; };
const logoutUser = async (userId) => { const logoutUser = async (userId) => {
try { try {
await UserModel.updateOne({ _id: userId }, { $unset: { authToken: null } }); await UserModel.updateOne({ _id: userId }, { $unset: { authToken: null } });
return true; return true;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "logoutUser"; error.method = "logoutUser";
throw error; throw error;
} }
}; };
export { export {
insertUser, insertUser,
getUserByEmail, getUserByEmail,
updateUser, updateUser,
deleteUser, deleteUser,
deleteTeam, deleteTeam,
deleteAllOtherUsers, deleteAllOtherUsers,
getAllUsers, getAllUsers,
logoutUser, logoutUser,
}; };
+8 -8
View File
@@ -2,14 +2,14 @@ import logger from "../utils/logger.js";
import { errorMessages } from "../utils/messages.js"; import { errorMessages } from "../utils/messages.js";
const handleErrors = (error, req, res, next) => { const handleErrors = (error, req, res, next) => {
const status = error.status || 500; const status = error.status || 500;
const message = error.message || errorMessages.FRIENDLY_ERROR; const message = error.message || errorMessages.FRIENDLY_ERROR;
const service = error.service || errorMessages.UNKNOWN_SERVICE; const service = error.service || errorMessages.UNKNOWN_SERVICE;
logger.error(error.message, { logger.error(error.message, {
service: service, service: service,
method: error.method, method: error.method,
}); });
res.status(status).json({ success: false, msg: message }); res.status(status).json({ success: false, msg: message });
}; };
export { handleErrors }; export { handleErrors };
+43 -43
View File
@@ -4,52 +4,52 @@ const SERVICE_NAME = "allowedRoles";
import { errorMessages } from "../utils/messages.js"; import { errorMessages } from "../utils/messages.js";
const isAllowed = (allowedRoles) => { const isAllowed = (allowedRoles) => {
return (req, res, next) => { return (req, res, next) => {
const token = req.headers["authorization"]; const token = req.headers["authorization"];
// If no token is pressent, return an error // If no token is pressent, return an error
if (!token) { if (!token) {
const error = new Error(errorMessages.NO_AUTH_TOKEN); const error = new Error(errorMessages.NO_AUTH_TOKEN);
error.status = 401; error.status = 401;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
next(error); next(error);
return; return;
} }
// If the token is improperly formatted, return an error // If the token is improperly formatted, return an error
if (!token.startsWith(TOKEN_PREFIX)) { if (!token.startsWith(TOKEN_PREFIX)) {
const error = new Error(errorMessages.INVALID_AUTH_TOKEN); const error = new Error(errorMessages.INVALID_AUTH_TOKEN);
error.status = 400; error.status = 400;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
next(error); next(error);
return; return;
} }
// Parse the token // Parse the token
try { try {
const parsedToken = token.slice(TOKEN_PREFIX.length, token.length); const parsedToken = token.slice(TOKEN_PREFIX.length, token.length);
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = req.settingsService.getSettings();
var decoded = jwt.verify(parsedToken, jwtSecret); var decoded = jwt.verify(parsedToken, jwtSecret);
const userRoles = decoded.role; const userRoles = decoded.role;
// Check if the user has the required role // Check if the user has the required role
if (userRoles.some((role) => allowedRoles.includes(role))) { if (userRoles.some((role) => allowedRoles.includes(role))) {
next(); next();
return; return;
} else { } else {
const error = new Error(errorMessages.INSUFFICIENT_PERMISSIONS); const error = new Error(errorMessages.INSUFFICIENT_PERMISSIONS);
error.status = 401; error.status = 401;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
next(error); next(error);
return; return;
} }
} catch (error) { } catch (error) {
error.status = 401; error.status = 401;
error.method = "isAllowed"; error.method = "isAllowed";
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
next(error); next(error);
return; return;
} }
}; };
}; };
export { isAllowed }; export { isAllowed };
+67 -69
View File
@@ -13,82 +13,80 @@ const TOKEN_PREFIX = "Bearer ";
* @returns {express.Response} * @returns {express.Response}
*/ */
const verifyJWT = (req, res, next) => { const verifyJWT = (req, res, next) => {
const token = req.headers["authorization"]; const token = req.headers["authorization"];
// Make sure a token is provided // Make sure a token is provided
if (!token) { if (!token) {
const error = new Error(errorMessages.NO_AUTH_TOKEN); const error = new Error(errorMessages.NO_AUTH_TOKEN);
error.status = 401; error.status = 401;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
next(error); next(error);
return; return;
} }
// Make sure it is properly formatted // Make sure it is properly formatted
if (!token.startsWith(TOKEN_PREFIX)) { if (!token.startsWith(TOKEN_PREFIX)) {
const error = new Error(errorMessages.INVALID_AUTH_TOKEN); // Instantiate a new Error object for improperly formatted token const error = new Error(errorMessages.INVALID_AUTH_TOKEN); // Instantiate a new Error object for improperly formatted token
error.status = 400; error.status = 400;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "verifyJWT"; error.method = "verifyJWT";
next(error); next(error);
return; return;
} }
const parsedToken = token.slice(TOKEN_PREFIX.length, token.length); const parsedToken = token.slice(TOKEN_PREFIX.length, token.length);
// Verify the token's authenticity // Verify the token's authenticity
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = req.settingsService.getSettings();
jwt.verify(parsedToken, jwtSecret, (err, decoded) => { jwt.verify(parsedToken, jwtSecret, (err, decoded) => {
if (err) { if (err) {
if (err.name === "TokenExpiredError") { if (err.name === "TokenExpiredError") {
// token has expired // token has expired
handleExpiredJwtToken(req, res, next); handleExpiredJwtToken(req, res, next);
} } else {
else { // Invalid token (signature or token altered or other issue)
// Invalid token (signature or token altered or other issue) const errorMessage = errorMessages.INVALID_AUTH_TOKEN;
const errorMessage = errorMessages.INVALID_AUTH_TOKEN; return res.status(401).json({ success: false, msg: errorMessage });
return res.status(401).json({ success: false, msg: errorMessage }); }
} } else {
} // Token is valid and not expired, carry on with request, Add the decoded payload to the request
else { req.user = decoded;
// Token is valid and not expired, carry on with request, Add the decoded payload to the request next();
req.user = decoded; }
next(); });
}
});
}; };
function handleExpiredJwtToken(req, res, next) { function handleExpiredJwtToken(req, res, next) {
// check for refreshToken // check for refreshToken
const refreshToken = req.headers["x-refresh-token"]; const refreshToken = req.headers["x-refresh-token"];
if (!refreshToken) { if (!refreshToken) {
// No refresh token provided // No refresh token provided
const error = new Error(errorMessages.NO_REFRESH_TOKEN); const error = new Error(errorMessages.NO_REFRESH_TOKEN);
error.status = 401; error.status = 401;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "handleExpiredJwtToken"; error.method = "handleExpiredJwtToken";
return next(error); return next(error);
} }
// Verify refresh token // Verify refresh token
const { refreshTokenSecret } = req.settingsService.getSettings(); const { refreshTokenSecret } = req.settingsService.getSettings();
jwt.verify(refreshToken, refreshTokenSecret, (refreshErr, refreshDecoded) => { jwt.verify(refreshToken, refreshTokenSecret, (refreshErr, refreshDecoded) => {
if (refreshErr) { if (refreshErr) {
// Invalid or expired refresh token, trigger logout // Invalid or expired refresh token, trigger logout
const errorMessage = const errorMessage =
refreshErr.name === "TokenExpiredError" refreshErr.name === "TokenExpiredError"
? errorMessages.EXPIRED_REFRESH_TOKEN ? errorMessages.EXPIRED_REFRESH_TOKEN
: errorMessages.INVALID_REFRESH_TOKEN; : errorMessages.INVALID_REFRESH_TOKEN;
const error = new Error(errorMessage); const error = new Error(errorMessage);
error.status = 401; error.status = 401;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
return next(error); return next(error);
} }
// Refresh token is valid and unexpired, request for new access token // Refresh token is valid and unexpired, request for new access token
res.status(403).json({ res.status(403).json({
success: false, success: false,
msg: errorMessages.REQUEST_NEW_ACCESS_TOKEN, msg: errorMessages.REQUEST_NEW_ACCESS_TOKEN,
}); });
}); });
} }
export { verifyJWT }; export { verifyJWT };
+39 -39
View File
@@ -3,47 +3,47 @@ import { errorMessages } from "../utils/messages.js";
const SERVICE_NAME = "verifyOwnership"; const SERVICE_NAME = "verifyOwnership";
const verifyOwnership = (Model, paramName) => { const verifyOwnership = (Model, paramName) => {
return async (req, res, next) => { return async (req, res, next) => {
const userId = req.user._id; const userId = req.user._id;
const documentId = req.params[paramName]; const documentId = req.params[paramName];
try { try {
const doc = await Model.findById(documentId); const doc = await Model.findById(documentId);
//If the document is not found, return a 404 error //If the document is not found, return a 404 error
if (!doc) { if (!doc) {
logger.error(errorMessages.VERIFY_OWNER_NOT_FOUND, { logger.error(errorMessages.VERIFY_OWNER_NOT_FOUND, {
service: SERVICE_NAME, service: SERVICE_NAME,
}); });
const error = new Error(errorMessages.VERIFY_OWNER_NOT_FOUND); const error = new Error(errorMessages.VERIFY_OWNER_NOT_FOUND);
error.status = 404; error.status = 404;
throw error; throw error;
} }
// Special case for User model, as it will not have a `userId` field as other docs will // Special case for User model, as it will not have a `userId` field as other docs will
if (Model.modelName === "User") { if (Model.modelName === "User") {
if (userId.toString() !== doc._id.toString()) { if (userId.toString() !== doc._id.toString()) {
const error = new Error(errorMessages.VERIFY_OWNER_UNAUTHORIZED); const error = new Error(errorMessages.VERIFY_OWNER_UNAUTHORIZED);
error.status = 403; error.status = 403;
throw error; throw error;
} }
next(); next();
return; return;
} }
// If the userID does not match the document's userID, return a 403 error // If the userID does not match the document's userID, return a 403 error
if (userId.toString() !== doc.userId.toString()) { if (userId.toString() !== doc.userId.toString()) {
const error = new Error(errorMessages.VERIFY_OWNER_UNAUTHORIZED); const error = new Error(errorMessages.VERIFY_OWNER_UNAUTHORIZED);
error.status = 403; error.status = 403;
throw error; throw error;
} }
next(); next();
return; return;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "verifyOwnership"; error.method = "verifyOwnership";
next(error); next(error);
return; return;
} }
}; };
}; };
export { verifyOwnership }; export { verifyOwnership };
+38 -40
View File
@@ -12,49 +12,47 @@ const { errorMessages } = require("../utils/messages");
* @returns {express.Response} * @returns {express.Response}
*/ */
const verifySuperAdmin = (req, res, next) => { const verifySuperAdmin = (req, res, next) => {
const token = req.headers["authorization"]; const token = req.headers["authorization"];
// Make sure a token is provided // Make sure a token is provided
if (!token) { if (!token) {
const error = new Error(errorMessages.NO_AUTH_TOKEN); const error = new Error(errorMessages.NO_AUTH_TOKEN);
error.status = 401; error.status = 401;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
next(error); next(error);
return; return;
} }
// Make sure it is properly formatted // Make sure it is properly formatted
if (!token.startsWith(TOKEN_PREFIX)) { if (!token.startsWith(TOKEN_PREFIX)) {
const error = new Error(errorMessages.INVALID_AUTH_TOKEN); // Instantiate a new Error object for improperly formatted token const error = new Error(errorMessages.INVALID_AUTH_TOKEN); // Instantiate a new Error object for improperly formatted token
error.status = 400; error.status = 400;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "verifySuperAdmin"; error.method = "verifySuperAdmin";
next(error); next(error);
return; return;
} }
const parsedToken = token.slice(TOKEN_PREFIX.length, token.length); const parsedToken = token.slice(TOKEN_PREFIX.length, token.length);
// verify admin role is present // verify admin role is present
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = req.settingsService.getSettings();
jwt.verify(parsedToken, jwtSecret, (err, decoded) => { jwt.verify(parsedToken, jwtSecret, (err, decoded) => {
if (err) { if (err) {
logger.error(errorMessages.INVALID_AUTH_TOKEN, { logger.error(errorMessages.INVALID_AUTH_TOKEN, {
service: SERVICE_NAME, service: SERVICE_NAME,
}); });
return res return res
.status(401) .status(401)
.json({ success: false, msg: errorMessages.INVALID_AUTH_TOKEN }); .json({ success: false, msg: errorMessages.INVALID_AUTH_TOKEN });
} }
if (decoded.role.includes("superadmin") === false) { if (decoded.role.includes("superadmin") === false) {
logger.error(errorMessages.INVALID_AUTH_TOKEN, { logger.error(errorMessages.INVALID_AUTH_TOKEN, {
service: SERVICE_NAME, service: SERVICE_NAME,
}); });
return res return res.status(401).json({ success: false, msg: errorMessages.UNAUTHORIZED });
.status(401) }
.json({ success: false, msg: errorMessages.UNAUTHORIZED }); next();
} });
next();
});
}; };
module.exports = { verifySuperAdmin }; module.exports = { verifySuperAdmin };
+2262 -2275
View File
File diff suppressed because it is too large. Load diff
+8 -16
View File
@@ -1,11 +1,11 @@
import { Router } from "express"; import { Router } from "express";
import { import {
createCheck, createCheck,
getChecks, getChecks,
deleteChecks, deleteChecks,
getTeamChecks, getTeamChecks,
deleteChecksByTeamId, deleteChecksByTeamId,
updateChecksTTL, updateChecksTTL,
} from "../controllers/checkController.js"; } from "../controllers/checkController.js";
import { verifyOwnership } from "../middleware/verifyOwnership.js"; import { verifyOwnership } from "../middleware/verifyOwnership.js";
import { isAllowed } from "../middleware/isAllowed.js"; import { isAllowed } from "../middleware/isAllowed.js";
@@ -15,19 +15,11 @@ const router = Router();
router.get("/:monitorId", getChecks); router.get("/:monitorId", getChecks);
router.post("/:monitorId", verifyOwnership(Monitor, "monitorId"), createCheck); router.post("/:monitorId", verifyOwnership(Monitor, "monitorId"), createCheck);
router.delete( router.delete("/:monitorId", verifyOwnership(Monitor, "monitorId"), deleteChecks);
"/:monitorId",
verifyOwnership(Monitor, "monitorId"),
deleteChecks
);
router.get("/team/:teamId", getTeamChecks); router.get("/team/:teamId", getTeamChecks);
router.delete( router.delete("/team/:teamId", isAllowed(["admin", "superadmin"]), deleteChecksByTeamId);
"/team/:teamId",
isAllowed(["admin", "superadmin"]),
deleteChecksByTeamId
);
router.put("/team/ttl", isAllowed(["admin", "superadmin"]), updateChecksTTL); router.put("/team/ttl", isAllowed(["admin", "superadmin"]), updateChecksTTL);
+3 -8
View File
@@ -2,18 +2,13 @@ import { Router } from "express";
import { verifyJWT } from "../middleware/verifyJWT.js"; import { verifyJWT } from "../middleware/verifyJWT.js";
import { isAllowed } from "../middleware/isAllowed.js"; import { isAllowed } from "../middleware/isAllowed.js";
import { import {
issueInvitation, issueInvitation,
inviteVerifyController, inviteVerifyController,
} from "../controllers/inviteController.js"; } from "../controllers/inviteController.js";
const router = Router(); const router = Router();
router.post( router.post("/", isAllowed(["admin", "superadmin"]), verifyJWT, issueInvitation);
"/",
isAllowed(["admin", "superadmin"]),
verifyJWT,
issueInvitation
);
router.post("/verify", issueInvitation); router.post("/verify", issueInvitation);
export default router; export default router;
+9 -9
View File
@@ -1,11 +1,11 @@
import { Router } from "express"; import { Router } from "express";
import { import {
createMaintenanceWindows, createMaintenanceWindows,
getMaintenanceWindowById, getMaintenanceWindowById,
getMaintenanceWindowsByTeamId, getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId, getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindow, deleteMaintenanceWindow,
editMaintenanceWindow, editMaintenanceWindow,
} from "../controllers/maintenanceWindowController.js"; } from "../controllers/maintenanceWindowController.js";
import { verifyOwnership } from "../middleware/verifyOwnership.js"; import { verifyOwnership } from "../middleware/verifyOwnership.js";
import Monitor from "../db/models/Monitor.js"; import Monitor from "../db/models/Monitor.js";
@@ -15,9 +15,9 @@ const router = Router();
router.post("/", createMaintenanceWindows); router.post("/", createMaintenanceWindows);
router.get( router.get(
"/monitor/:monitorId", "/monitor/:monitorId",
verifyOwnership(Monitor, "monitorId"), verifyOwnership(Monitor, "monitorId"),
getMaintenanceWindowsByMonitorId getMaintenanceWindowsByMonitorId
); );
router.get("/team/", getMaintenanceWindowsByTeamId); router.get("/team/", getMaintenanceWindowsByTeamId);
+4 -4
View File
@@ -1,9 +1,9 @@
import { Router } from "express"; import { Router } from "express";
import { import {
getMetrics, getMetrics,
getJobs, getJobs,
addJob, addJob,
obliterateQueue, obliterateQueue,
} from "../controllers/queueController.js"; } from "../controllers/queueController.js";
const router = Router(); const router = Router();
+1 -4
View File
@@ -1,8 +1,5 @@
import { Router } from "express"; import { Router } from "express";
import { import { getAppSettings, updateAppSettings } from "../controllers/settingsController.js";
getAppSettings,
updateAppSettings,
} from "../controllers/settingsController.js";
import { isAllowed } from "../middleware/isAllowed.js"; import { isAllowed } from "../middleware/isAllowed.js";
const router = Router(); const router = Router();
+104 -115
View File
@@ -15,128 +15,117 @@ const SERVICE_NAME = "EmailService";
* Represents an email service that can load templates, build, and send emails. * Represents an email service that can load templates, build, and send emails.
*/ */
class EmailService { class EmailService {
/** /**
* Constructs an instance of the EmailService, initializing template loaders and the email transporter. * Constructs an instance of the EmailService, initializing template loaders and the email transporter.
*/ */
constructor(settingsService) { constructor(settingsService) {
this.settingsService = settingsService; this.settingsService = settingsService;
/** /**
* Loads an email template from the filesystem. * Loads an email template from the filesystem.
* *
* @param {string} templateName - The name of the template to load. * @param {string} templateName - The name of the template to load.
* @returns {Function} A compiled template function that can be used to generate HTML email content. * @returns {Function} A compiled template function that can be used to generate HTML email content.
*/ */
this.loadTemplate = (templateName) => { this.loadTemplate = (templateName) => {
try { try {
const templatePath = path.join( const templatePath = path.join(__dirname, `../templates/${templateName}.mjml`);
__dirname, const templateContent = fs.readFileSync(templatePath, "utf8");
`../templates/${templateName}.mjml` return compile(templateContent);
); } catch (error) {
const templateContent = fs.readFileSync(templatePath, "utf8"); logger.error("Error loading Email templates", {
return compile(templateContent); error,
} catch (error) { service: this.SERVICE_NAME,
logger.error("Error loading Email templates", { });
error, }
service: this.SERVICE_NAME, };
});
}
};
/** /**
* A lookup object to access preloaded email templates. * A lookup object to access preloaded email templates.
* @type {Object.<string, Function>} * @type {Object.<string, Function>}
* TODO Load less used templates in their respective functions * TODO Load less used templates in their respective functions
*/ */
this.templateLookup = { this.templateLookup = {
welcomeEmailTemplate: this.loadTemplate("welcomeEmail"), welcomeEmailTemplate: this.loadTemplate("welcomeEmail"),
employeeActivationTemplate: this.loadTemplate("employeeActivation"), employeeActivationTemplate: this.loadTemplate("employeeActivation"),
noIncidentsThisWeekTemplate: this.loadTemplate("noIncidentsThisWeek"), noIncidentsThisWeekTemplate: this.loadTemplate("noIncidentsThisWeek"),
serverIsDownTemplate: this.loadTemplate("serverIsDown"), serverIsDownTemplate: this.loadTemplate("serverIsDown"),
serverIsUpTemplate: this.loadTemplate("serverIsUp"), serverIsUpTemplate: this.loadTemplate("serverIsUp"),
passwordResetTemplate: this.loadTemplate("passwordReset"), passwordResetTemplate: this.loadTemplate("passwordReset"),
}; };
/** /**
* The email transporter used to send emails. * The email transporter used to send emails.
* @type {Object} * @type {Object}
*/ */
const { const { systemEmailHost, systemEmailPort, systemEmailAddress, systemEmailPassword } =
systemEmailHost, this.settingsService.getSettings();
systemEmailPort,
systemEmailAddress,
systemEmailPassword,
} = this.settingsService.getSettings();
const emailConfig = { const emailConfig = {
host: systemEmailHost, host: systemEmailHost,
port: systemEmailPort, port: systemEmailPort,
secure: true, secure: true,
auth: { auth: {
user: systemEmailAddress, user: systemEmailAddress,
pass: systemEmailPassword, pass: systemEmailPassword,
}, },
}; };
this.transporter = nodemailer.createTransport(emailConfig); this.transporter = nodemailer.createTransport(emailConfig);
} }
/** /**
* Asynchronously builds and sends an email using a specified template and context. * Asynchronously builds and sends an email using a specified template and context.
* *
* @param {string} template - The name of the template to use for the email body. * @param {string} template - The name of the template to use for the email body.
* @param {Object} context - The data context to render the template with. * @param {Object} context - The data context to render the template with.
* @param {string} to - The recipient's email address. * @param {string} to - The recipient's email address.
* @param {string} subject - The subject of the email. * @param {string} subject - The subject of the email.
* @returns {Promise<string>} A promise that resolves to the messageId of the sent email. * @returns {Promise<string>} A promise that resolves to the messageId of the sent email.
*/ */
buildAndSendEmail = async (template, context, to, subject) => { buildAndSendEmail = async (template, context, to, subject) => {
const buildHtml = async (template, context) => { const buildHtml = async (template, context) => {
try { try {
const mjml = this.templateLookup[template](context); const mjml = this.templateLookup[template](context);
const html = await mjml2html(mjml); const html = await mjml2html(mjml);
return html.html; return html.html;
} catch (error) { } catch (error) {
logger.error("Error building Email HTML", { logger.error("Error building Email HTML", {
error, error,
service: SERVICE_NAME, service: SERVICE_NAME,
}); });
} }
}; };
const sendEmail = async (to, subject, html) => { const sendEmail = async (to, subject, html) => {
try { try {
const info = await this.transporter.sendMail({ const info = await this.transporter.sendMail({
to: to, to: to,
subject: subject, subject: subject,
html: html, html: html,
}); });
return info; return info;
} catch (error) { } catch (error) {
logger.error("Error sending Email", { logger.error("Error sending Email", {
error, error,
service: SERVICE_NAME, service: SERVICE_NAME,
}); });
} }
}; };
try { try {
const info = await sendEmail( const info = await sendEmail(to, subject, await buildHtml(template, context));
to, return info.messageId;
subject, } catch (error) {
await buildHtml(template, context) error.service = SERVICE_NAME;
); if (error.method === undefined) {
return info.messageId; error.method = "buildAndSendEmail";
} catch (error) { }
error.service = SERVICE_NAME; logger.error("Error building and sending Email", {
if (error.method === undefined) { error,
error.method = "buildAndSendEmail"; service: SERVICE_NAME,
} });
logger.error("Error building and sending Email", { }
error, };
service: SERVICE_NAME,
});
}
};
} }
export default EmailService; export default EmailService;
+311 -315
View File
@@ -13,145 +13,142 @@ const SERVICE_NAME = "JobQueue";
* It scales the number of workers based on the number of jobs/worker * It scales the number of workers based on the number of jobs/worker
*/ */
class JobQueue { class JobQueue {
/** /**
* Constructs a new JobQueue * Constructs a new JobQueue
* @constructor * @constructor
* @param {SettingsService} settingsService - The settings service * @param {SettingsService} settingsService - The settings service
* @throws {Error} * @throws {Error}
*/ */
constructor(settingsService) { constructor(settingsService) {
const { redisHost, redisPort } = settingsService.getSettings(); const { redisHost, redisPort } = settingsService.getSettings();
const connection = { const connection = {
host: redisHost || "127.0.0.1", host: redisHost || "127.0.0.1",
port: redisPort || 6379, port: redisPort || 6379,
}; };
this.connection = connection; this.connection = connection;
this.queue = new Queue(QUEUE_NAME, { this.queue = new Queue(QUEUE_NAME, {
connection, connection,
}); });
this.workers = []; this.workers = [];
this.db = null; this.db = null;
this.networkService = null; this.networkService = null;
this.settingsService = settingsService; this.settingsService = settingsService;
} }
/** /**
* Static factory method to create a JobQueue * Static factory method to create a JobQueue
* @static * @static
* @async * @async
* @returns {Promise<JobQueue>} - Returns a new JobQueue * @returns {Promise<JobQueue>} - Returns a new JobQueue
* *
*/ */
static async createJobQueue(db, networkService, settingsService) { static async createJobQueue(db, networkService, settingsService) {
const queue = new JobQueue(settingsService); const queue = new JobQueue(settingsService);
try { try {
queue.db = db; queue.db = db;
queue.networkService = networkService; queue.networkService = networkService;
const monitors = await db.getAllMonitors(); const monitors = await db.getAllMonitors();
for (const monitor of monitors) { for (const monitor of monitors) {
if (monitor.isActive) { if (monitor.isActive) {
await queue.addJob(monitor.id, monitor); await queue.addJob(monitor.id, monitor);
} }
} }
const workerStats = await queue.getWorkerStats(); const workerStats = await queue.getWorkerStats();
await queue.scaleWorkers(workerStats); await queue.scaleWorkers(workerStats);
return queue; return queue;
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "createJobQueue") : null; error.method === undefined ? (error.method = "createJobQueue") : null;
throw error; throw error;
} }
} }
/** /**
* Creates a worker for the queue * Creates a worker for the queue
* Operations are carried out in the async callback * Operations are carried out in the async callback
* @returns {Worker} The newly created worker * @returns {Worker} The newly created worker
*/ */
createWorker() { createWorker() {
const worker = new Worker( const worker = new Worker(
QUEUE_NAME, QUEUE_NAME,
async (job) => { async (job) => {
try { try {
// Get all maintenance windows for this monitor // Get all maintenance windows for this monitor
const monitorId = job.data._id; const monitorId = job.data._id;
const maintenanceWindows = const maintenanceWindows =
await this.db.getMaintenanceWindowsByMonitorId(monitorId); await this.db.getMaintenanceWindowsByMonitorId(monitorId);
// Check for active maintenance window: // Check for active maintenance window:
const maintenanceWindowActive = maintenanceWindows.reduce( const maintenanceWindowActive = maintenanceWindows.reduce((acc, window) => {
(acc, window) => { if (window.active) {
if (window.active) { const start = new Date(window.start);
const start = new Date(window.start); const end = new Date(window.end);
const end = new Date(window.end); const now = new Date();
const now = new Date(); const repeatInterval = window.repeat || 0;
const repeatInterval = window.repeat || 0;
while ((start < now) & (repeatInterval !== 0)) { while ((start < now) & (repeatInterval !== 0)) {
start.setTime(start.getTime() + repeatInterval); start.setTime(start.getTime() + repeatInterval);
end.setTime(end.getTime() + repeatInterval); end.setTime(end.getTime() + repeatInterval);
} }
if (start < now && end > now) { if (start < now && end > now) {
return true; return true;
} }
} }
return acc; return acc;
}, }, false);
false
);
if (!maintenanceWindowActive) { if (!maintenanceWindowActive) {
const res = await this.networkService.getStatus(job); const res = await this.networkService.getStatus(job);
} else { } else {
logger.info(`Monitor ${monitorId} is in maintenance window`, { logger.info(`Monitor ${monitorId} is in maintenance window`, {
service: SERVICE_NAME, service: SERVICE_NAME,
monitorId, monitorId,
}); });
} }
} catch (error) { } catch (error) {
logger.error(`Error processing job ${job.id}: ${error.message}`, { logger.error(`Error processing job ${job.id}: ${error.message}`, {
service: SERVICE_NAME, service: SERVICE_NAME,
jobId: job.id, jobId: job.id,
error: error, error: error,
}); });
} }
}, },
{ {
connection: this.connection, connection: this.connection,
} }
); );
return worker; return worker;
} }
/** /**
* @typedef {Object} WorkerStats * @typedef {Object} WorkerStats
* @property {Array<Job>} jobs - Array of jobs in the Queue * @property {Array<Job>} jobs - Array of jobs in the Queue
* @property {number} - workerLoad - The number of jobs per worker * @property {number} - workerLoad - The number of jobs per worker
* *
*/ */
/** /**
* Gets stats related to the workers * Gets stats related to the workers
* This is used for scaling workers right now * This is used for scaling workers right now
* In the future we will likely want to scale based on server performance metrics * In the future we will likely want to scale based on server performance metrics
* CPU Usage & memory usage, if too high, scale down workers. * CPU Usage & memory usage, if too high, scale down workers.
* When to scale up? If jobs are taking too long to complete? * When to scale up? If jobs are taking too long to complete?
* @async * @async
* @returns {Promise<WorkerStats>} - Returns the worker stats * @returns {Promise<WorkerStats>} - Returns the worker stats
*/ */
async getWorkerStats() { async getWorkerStats() {
try { try {
const jobs = await this.queue.getRepeatableJobs(); const jobs = await this.queue.getRepeatableJobs();
const load = jobs.length / this.workers.length; const load = jobs.length / this.workers.length;
return { jobs, load }; return { jobs, load };
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getWorkerStats") : null; error.method === undefined ? (error.method = "getWorkerStats") : null;
throw error; throw error;
} }
} }
/** /**
* Scale Workers * Scale Workers
* This function scales workers based on the load per worker * This function scales workers based on the load per worker
* If the load is higher than the JOBS_PER_WORKER threshold, we add more workers * If the load is higher than the JOBS_PER_WORKER threshold, we add more workers
@@ -163,201 +160,200 @@ class JobQueue {
* @param {WorkerStats} workerStats - The payload for the job. * @param {WorkerStats} workerStats - The payload for the job.
* @returns {Promise<boolean>} * @returns {Promise<boolean>}
*/ */
async scaleWorkers(workerStats) { async scaleWorkers(workerStats) {
if (this.workers.length === 0) { if (this.workers.length === 0) {
// There are no workers, need to add one // There are no workers, need to add one
for (let i = 0; i < 5; i++) { for (let i = 0; i < 5; i++) {
const worker = this.createWorker(); const worker = this.createWorker();
this.workers.push(worker); this.workers.push(worker);
} }
return true; return true;
} }
if (workerStats.load > JOBS_PER_WORKER) { if (workerStats.load > JOBS_PER_WORKER) {
// Find out how many more jobs we have than current workers can handle // Find out how many more jobs we have than current workers can handle
const excessJobs = const excessJobs = workerStats.jobs.length - this.workers.length * JOBS_PER_WORKER;
workerStats.jobs.length - this.workers.length * JOBS_PER_WORKER;
// Divide by jobs/worker to find out how many workers to add // Divide by jobs/worker to find out how many workers to add
const workersToAdd = Math.ceil(excessJobs / JOBS_PER_WORKER); const workersToAdd = Math.ceil(excessJobs / JOBS_PER_WORKER);
for (let i = 0; i < workersToAdd; i++) { for (let i = 0; i < workersToAdd; i++) {
const worker = this.createWorker(); const worker = this.createWorker();
this.workers.push(worker); this.workers.push(worker);
} }
return true; return true;
} }
if (workerStats.load < JOBS_PER_WORKER) { if (workerStats.load < JOBS_PER_WORKER) {
// Find out how much excess capacity we have // Find out how much excess capacity we have
const workerCapacity = this.workers.length * JOBS_PER_WORKER; const workerCapacity = this.workers.length * JOBS_PER_WORKER;
const excessCapacity = workerCapacity - workerStats.jobs.length; const excessCapacity = workerCapacity - workerStats.jobs.length;
// Calculate how many workers to remove // Calculate how many workers to remove
const workersToRemove = Math.floor(excessCapacity / JOBS_PER_WORKER); const workersToRemove = Math.floor(excessCapacity / JOBS_PER_WORKER);
if (this.workers.length > 5) { if (this.workers.length > 5) {
for (let i = 0; i < workersToRemove; i++) { for (let i = 0; i < workersToRemove; i++) {
const worker = this.workers.pop(); const worker = this.workers.pop();
try { try {
await worker.close(); await worker.close();
} catch (error) { } catch (error) {
// Catch the error instead of throwing it // Catch the error instead of throwing it
logger.error(errorMessages.JOB_QUEUE_WORKER_CLOSE, { logger.error(errorMessages.JOB_QUEUE_WORKER_CLOSE, {
service: SERVICE_NAME, service: SERVICE_NAME,
}); });
} }
} }
} }
return true; return true;
} }
return false; return false;
} }
/** /**
* Gets all jobs in the queue. * Gets all jobs in the queue.
* *
* @async * @async
* @returns {Promise<Array<Job>>} * @returns {Promise<Array<Job>>}
* @throws {Error} - Throws error if getting jobs fails * @throws {Error} - Throws error if getting jobs fails
*/ */
async getJobs() { async getJobs() {
try { try {
const jobs = await this.queue.getRepeatableJobs(); const jobs = await this.queue.getRepeatableJobs();
return jobs; return jobs;
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getJobs") : null; error.method === undefined ? (error.method = "getJobs") : null;
throw error; throw error;
} }
} }
async getJobStats() { async getJobStats() {
try { try {
const jobs = await this.queue.getJobs(); const jobs = await this.queue.getJobs();
const ret = await Promise.all( const ret = await Promise.all(
jobs.map(async (job) => { jobs.map(async (job) => {
const state = await job.getState(); const state = await job.getState();
return { url: job.data.url, state }; return { url: job.data.url, state };
}) })
); );
return { jobs: ret, workers: this.workers.length }; return { jobs: ret, workers: this.workers.length };
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getJobStats") : null; error.method === undefined ? (error.method = "getJobStats") : null;
throw error; throw error;
} }
} }
/** /**
* Adds a job to the queue and scales workers based on worker stats. * Adds a job to the queue and scales workers based on worker stats.
* *
* @async * @async
* @param {string} jobName - The name of the job to be added. * @param {string} jobName - The name of the job to be added.
* @param {Monitor} payload - The payload for the job. * @param {Monitor} payload - The payload for the job.
* @throws {Error} - Will throw an error if the job cannot be added or workers don't scale * @throws {Error} - Will throw an error if the job cannot be added or workers don't scale
*/ */
async addJob(jobName, payload) { async addJob(jobName, payload) {
try { try {
console.log("Adding job", payload?.url ?? "No URL"); console.log("Adding job", payload?.url ?? "No URL");
// Execute job immediately // Execute job immediately
await this.queue.add(jobName, payload); await this.queue.add(jobName, payload);
await this.queue.add(jobName, payload, { await this.queue.add(jobName, payload, {
repeat: { repeat: {
every: payload?.interval ?? 60000, every: payload?.interval ?? 60000,
}, },
}); });
const workerStats = await this.getWorkerStats(); const workerStats = await this.getWorkerStats();
await this.scaleWorkers(workerStats); await this.scaleWorkers(workerStats);
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "addJob") : null; error.method === undefined ? (error.method = "addJob") : null;
throw error; throw error;
} }
} }
/** /**
* Deletes a job from the queue. * Deletes a job from the queue.
* *
* @async * @async
* @param {Monitor} monitor - The monitor to remove. * @param {Monitor} monitor - The monitor to remove.
* @throws {Error} * @throws {Error}
*/ */
async deleteJob(monitor) { async deleteJob(monitor) {
try { try {
const deleted = await this.queue.removeRepeatable(monitor._id, { const deleted = await this.queue.removeRepeatable(monitor._id, {
every: monitor.interval, every: monitor.interval,
}); });
if (deleted) { if (deleted) {
logger.info(successMessages.JOB_QUEUE_DELETE_JOB, { logger.info(successMessages.JOB_QUEUE_DELETE_JOB, {
service: SERVICE_NAME, service: SERVICE_NAME,
jobId: monitor.id, jobId: monitor.id,
}); });
const workerStats = await this.getWorkerStats(); const workerStats = await this.getWorkerStats();
await this.scaleWorkers(workerStats); await this.scaleWorkers(workerStats);
} else { } else {
logger.error(errorMessages.JOB_QUEUE_DELETE_JOB, { logger.error(errorMessages.JOB_QUEUE_DELETE_JOB, {
service: SERVICE_NAME, service: SERVICE_NAME,
jobId: monitor.id, jobId: monitor.id,
}); });
} }
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "deleteJob") : null; error.method === undefined ? (error.method = "deleteJob") : null;
throw error; throw error;
} }
} }
async getMetrics() { async getMetrics() {
try { try {
const metrics = { const metrics = {
waiting: await this.queue.getWaitingCount(), waiting: await this.queue.getWaitingCount(),
active: await this.queue.getActiveCount(), active: await this.queue.getActiveCount(),
completed: await this.queue.getCompletedCount(), completed: await this.queue.getCompletedCount(),
failed: await this.queue.getFailedCount(), failed: await this.queue.getFailedCount(),
delayed: await this.queue.getDelayedCount(), delayed: await this.queue.getDelayedCount(),
repeatableJobs: (await this.queue.getRepeatableJobs()).length, repeatableJobs: (await this.queue.getRepeatableJobs()).length,
}; };
return metrics; return metrics;
} catch (error) { } catch (error) {
logger.error("Failed to retrieve job queue metrics", { logger.error("Failed to retrieve job queue metrics", {
service: SERVICE_NAME, service: SERVICE_NAME,
errorMsg: error.message, errorMsg: error.message,
}); });
} }
} }
/** /**
* @async * @async
* @returns {Promise<boolean>} - Returns true if obliteration is successful * @returns {Promise<boolean>} - Returns true if obliteration is successful
*/ */
async obliterate() { async obliterate() {
try { try {
let metrics = await this.getMetrics(); let metrics = await this.getMetrics();
console.log(metrics); console.log(metrics);
await this.queue.pause(); await this.queue.pause();
const jobs = await this.getJobs(); const jobs = await this.getJobs();
for (const job of jobs) { for (const job of jobs) {
await this.queue.removeRepeatableByKey(job.key); await this.queue.removeRepeatableByKey(job.key);
await this.queue.remove(job.id); await this.queue.remove(job.id);
} }
await Promise.all( await Promise.all(
this.workers.map(async (worker) => { this.workers.map(async (worker) => {
await worker.close(); await worker.close();
}) })
); );
await this.queue.obliterate(); await this.queue.obliterate();
metrics = await this.getMetrics(); metrics = await this.getMetrics();
console.log(metrics); console.log(metrics);
logger.info(successMessages.JOB_QUEUE_OBLITERATE, { logger.info(successMessages.JOB_QUEUE_OBLITERATE, {
service: SERVICE_NAME, service: SERVICE_NAME,
}); });
return true; return true;
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "obliterate") : null; error.method === undefined ? (error.method = "obliterate") : null;
throw error; throw error;
} }
} }
} }
export default JobQueue; export default JobQueue;
+287 -294
View File
@@ -12,321 +12,314 @@ import { errorMessages, successMessages } from "../utils/messages.js";
*/ */
class NetworkService { class NetworkService {
constructor(db, emailService) { constructor(db, emailService) {
this.db = db; this.db = db;
this.emailService = emailService; this.emailService = emailService;
this.TYPE_PING = "ping"; this.TYPE_PING = "ping";
this.TYPE_HTTP = "http"; this.TYPE_HTTP = "http";
this.TYPE_PAGESPEED = "pagespeed"; this.TYPE_PAGESPEED = "pagespeed";
this.SERVICE_NAME = "NetworkService"; this.SERVICE_NAME = "NetworkService";
this.NETWORK_ERROR = 5000; this.NETWORK_ERROR = 5000;
} }
async handleNotification(monitor, isAlive) { async handleNotification(monitor, isAlive) {
try { try {
let template = let template = isAlive === true ? "serverIsUpTemplate" : "serverIsDownTemplate";
isAlive === true ? "serverIsUpTemplate" : "serverIsDownTemplate"; let status = isAlive === true ? "up" : "down";
let status = isAlive === true ? "up" : "down";
const notifications = await this.db.getNotificationsByMonitorId( const notifications = await this.db.getNotificationsByMonitorId(monitor._id);
monitor._id for (const notification of notifications) {
); if (notification.type === "email") {
for (const notification of notifications) { await this.emailService.buildAndSendEmail(
if (notification.type === "email") { template,
await this.emailService.buildAndSendEmail( { monitorName: monitor.name, monitorUrl: monitor.url },
template, notification.address,
{ monitorName: monitor.name, monitorUrl: monitor.url }, `Monitor ${monitor.name} is ${status}`
notification.address, );
`Monitor ${monitor.name} is ${status}` }
); }
} } catch (error) {
} logger.error(error.message, {
} catch (error) { method: "handleNotification",
logger.error(error.message, { service: this.SERVICE_NAME,
method: "handleNotification", monitorId: monitor._id,
service: this.SERVICE_NAME, });
monitorId: monitor._id, }
}); }
}
}
async handleStatusUpdate(job, isAlive) { async handleStatusUpdate(job, isAlive) {
let monitor; let monitor;
// Look up the monitor, if it doesn't exist, it's probably been removed, return // Look up the monitor, if it doesn't exist, it's probably been removed, return
try { try {
const { _id } = job.data; const { _id } = job.data;
monitor = await this.db.getMonitorById(_id); monitor = await this.db.getMonitorById(_id);
} catch (error) { } catch (error) {
return; return;
} }
// Otherwise, try to update monitor status // Otherwise, try to update monitor status
try { try {
if (monitor === null || monitor === undefined) { if (monitor === null || monitor === undefined) {
logger.error(`Null Monitor: ${_id}`, { logger.error(`Null Monitor: ${_id}`, {
method: "handleStatusUpdate", method: "handleStatusUpdate",
service: this.SERVICE_NAME, service: this.SERVICE_NAME,
jobId: job.id, jobId: job.id,
}); });
return; return;
} }
if (monitor.status === undefined || monitor.status !== isAlive) { if (monitor.status === undefined || monitor.status !== isAlive) {
const oldStatus = monitor.status; const oldStatus = monitor.status;
monitor.status = isAlive; monitor.status = isAlive;
await monitor.save(); await monitor.save();
if (oldStatus !== undefined && oldStatus !== isAlive) { if (oldStatus !== undefined && oldStatus !== isAlive) {
this.handleNotification(monitor, isAlive); this.handleNotification(monitor, isAlive);
} }
} }
} catch (error) { } catch (error) {
logger.error(error.message, { logger.error(error.message, {
method: "handleStatusUpdate", method: "handleStatusUpdate",
service: this.SERVICE_NAME, service: this.SERVICE_NAME,
jobId: job.id, jobId: job.id,
}); });
} }
} }
/** /**
* Measures the response time of an asynchronous operation. * Measures the response time of an asynchronous operation.
* @param {Function} operation - An asynchronous operation to measure. * @param {Function} operation - An asynchronous operation to measure.
* @returns {Promise<{responseTime: number, response: any}>} An object containing the response time in milliseconds and the response from the operation. * @returns {Promise<{responseTime: number, response: any}>} An object containing the response time in milliseconds and the response from the operation.
* @throws {Error} The error object from the operation, contains response time. * @throws {Error} The error object from the operation, contains response time.
*/ */
async measureResponseTime(operation) { async measureResponseTime(operation) {
const startTime = Date.now(); const startTime = Date.now();
try { try {
const response = await operation(); const response = await operation();
const endTime = Date.now(); const endTime = Date.now();
return { responseTime: endTime - startTime, response }; return { responseTime: endTime - startTime, response };
} catch (error) { } catch (error) {
const endTime = Date.now(); const endTime = Date.now();
error.responseTime = endTime - startTime; error.responseTime = endTime - startTime;
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined error.method === undefined ? (error.method = "measureResponseTime") : null;
? (error.method = "measureResponseTime") throw error;
: null; }
throw error; }
}
}
/** /**
* Handles the ping operation for a given job, measures its response time, and logs the result. * Handles the ping operation for a given job, measures its response time, and logs the result.
* @param {Object} job - The job object containing data for the ping operation. * @param {Object} job - The job object containing data for the ping operation.
* @returns {Promise<{boolean}} The result of logging and storing the check * @returns {Promise<{boolean}} The result of logging and storing the check
*/ */
async handlePing(job) { async handlePing(job) {
const operation = async () => { const operation = async () => {
const response = await ping.promise.probe(job.data.url); const response = await ping.promise.probe(job.data.url);
return response; return response;
}; };
let isAlive; let isAlive;
try { try {
const { responseTime, response } = const { responseTime, response } = await this.measureResponseTime(operation);
await this.measureResponseTime(operation); isAlive = response.alive;
isAlive = response.alive; const checkData = {
const checkData = { monitorId: job.data._id,
monitorId: job.data._id, status: isAlive,
status: isAlive, responseTime,
responseTime, message: isAlive
message: isAlive ? successMessages.PING_SUCCESS
? successMessages.PING_SUCCESS : errorMessages.PING_CANNOT_RESOLVE,
: errorMessages.PING_CANNOT_RESOLVE, };
}; return await this.logAndStoreCheck(checkData, this.db.createCheck);
return await this.logAndStoreCheck(checkData, this.db.createCheck); } catch (error) {
} catch (error) { isAlive = false;
isAlive = false; const checkData = {
const checkData = { monitorId: job.data._id,
monitorId: job.data._id, status: isAlive,
status: isAlive, message: errorMessages.PING_CANNOT_RESOLVE,
message: errorMessages.PING_CANNOT_RESOLVE, responseTime: error.responseTime,
responseTime: error.responseTime, };
}; return await this.logAndStoreCheck(checkData, this.db.createCheck);
return await this.logAndStoreCheck(checkData, this.db.createCheck); } finally {
} finally { this.handleStatusUpdate(job, isAlive);
this.handleStatusUpdate(job, isAlive); }
} }
}
/** /**
* Handles the http operation for a given job, measures its response time, and logs the result. * Handles the http operation for a given job, measures its response time, and logs the result.
* @param {Object} job - The job object containing data for the ping operation. * @param {Object} job - The job object containing data for the ping operation.
* @returns {Promise<{boolean}} The result of logging and storing the check * @returns {Promise<{boolean}} The result of logging and storing the check
*/ */
async handleHttp(job) { async handleHttp(job) {
// Define operation for timing // Define operation for timing
const operation = async () => { const operation = async () => {
const response = await axios.get(job.data.url); const response = await axios.get(job.data.url);
return response; return response;
}; };
let isAlive; let isAlive;
// attempt connection // attempt connection
try { try {
const { responseTime, response } = const { responseTime, response } = await this.measureResponseTime(operation);
await this.measureResponseTime(operation); // check if response is in the 200 range, if so, service is up
// check if response is in the 200 range, if so, service is up isAlive = response.status >= 200 && response.status < 300;
isAlive = response.status >= 200 && response.status < 300;
//Create a check with relevant data //Create a check with relevant data
const checkData = { const checkData = {
monitorId: job.data._id, monitorId: job.data._id,
status: isAlive, status: isAlive,
responseTime, responseTime,
statusCode: response.status, statusCode: response.status,
message: http.STATUS_CODES[response.status], message: http.STATUS_CODES[response.status],
}; };
return await this.logAndStoreCheck(checkData, this.db.createCheck); return await this.logAndStoreCheck(checkData, this.db.createCheck);
} catch (error) { } catch (error) {
const statusCode = error.response?.status || this.NETWORK_ERROR; const statusCode = error.response?.status || this.NETWORK_ERROR;
let message = http.STATUS_CODES[statusCode] || "Network Error"; let message = http.STATUS_CODES[statusCode] || "Network Error";
isAlive = false; isAlive = false;
const checkData = { const checkData = {
monitorId: job.data._id, monitorId: job.data._id,
status: isAlive, status: isAlive,
statusCode, statusCode,
responseTime: error.responseTime, responseTime: error.responseTime,
message, message,
}; };
return await this.logAndStoreCheck(checkData, this.db.createCheck); return await this.logAndStoreCheck(checkData, this.db.createCheck);
} finally { } finally {
this.handleStatusUpdate(job, isAlive); this.handleStatusUpdate(job, isAlive);
} }
} }
/** /**
* Handles PageSpeed job types by fetching and processing PageSpeed insights. * Handles PageSpeed job types by fetching and processing PageSpeed insights.
* *
* This method sends a request to the Google PageSpeed Insights API to get performance metrics * This method sends a request to the Google PageSpeed Insights API to get performance metrics
* for the specified URL, then logs and stores the check results. * for the specified URL, then logs and stores the check results.
* *
* @param {Object} job - The job object containing data related to the PageSpeed check. * @param {Object} job - The job object containing data related to the PageSpeed check.
* @param {string} job.data.url - The URL to be analyzed by the PageSpeed Insights API. * @param {string} job.data.url - The URL to be analyzed by the PageSpeed Insights API.
* @param {string} job.data._id - The unique identifier for the monitor associated with the check. * @param {string} job.data._id - The unique identifier for the monitor associated with the check.
* *
* @returns {Promise<void>} A promise that resolves when the check results have been logged and stored. * @returns {Promise<void>} A promise that resolves when the check results have been logged and stored.
* *
* @throws {Error} Throws an error if there is an issue with fetching or processing the PageSpeed insights. * @throws {Error} Throws an error if there is an issue with fetching or processing the PageSpeed insights.
*/ */
async handlePagespeed(job) { async handlePagespeed(job) {
let isAlive; let isAlive;
try { try {
const url = job.data.url; const url = job.data.url;
const response = await axios.get( const response = await axios.get(
`https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=${url}&category=seo&category=accessibility&category=best-practices&category=performance` `https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=${url}&category=seo&category=accessibility&category=best-practices&category=performance`
); );
const pageSpeedResults = response.data; const pageSpeedResults = response.data;
const categories = pageSpeedResults.lighthouseResult?.categories; const categories = pageSpeedResults.lighthouseResult?.categories;
const audits = pageSpeedResults.lighthouseResult?.audits; const audits = pageSpeedResults.lighthouseResult?.audits;
const { const {
"cumulative-layout-shift": cls, "cumulative-layout-shift": cls,
"speed-index": si, "speed-index": si,
"first-contentful-paint": fcp, "first-contentful-paint": fcp,
"largest-contentful-paint": lcp, "largest-contentful-paint": lcp,
"total-blocking-time": tbt, "total-blocking-time": tbt,
} = audits; } = audits;
// Weights // Weights
// First Contentful Paint 10% // First Contentful Paint 10%
// Speed Index 10% // Speed Index 10%
// Largest Contentful Paint 25% // Largest Contentful Paint 25%
// Total Blocking Time 30% // Total Blocking Time 30%
// Cumulative Layout Shift 25% // Cumulative Layout Shift 25%
isAlive = true; isAlive = true;
const checkData = { const checkData = {
monitorId: job.data._id, monitorId: job.data._id,
status: isAlive, status: isAlive,
statusCode: response.status, statusCode: response.status,
message: http.STATUS_CODES[response.status], message: http.STATUS_CODES[response.status],
accessibility: (categories.accessibility?.score || 0) * 100, accessibility: (categories.accessibility?.score || 0) * 100,
bestPractices: (categories["best-practices"]?.score || 0) * 100, bestPractices: (categories["best-practices"]?.score || 0) * 100,
seo: (categories.seo?.score || 0) * 100, seo: (categories.seo?.score || 0) * 100,
performance: (categories.performance?.score || 0) * 100, performance: (categories.performance?.score || 0) * 100,
audits: { audits: {
cls, cls,
si, si,
fcp, fcp,
lcp, lcp,
tbt, tbt,
}, },
}; };
this.logAndStoreCheck(checkData, this.db.createPageSpeedCheck); this.logAndStoreCheck(checkData, this.db.createPageSpeedCheck);
} catch (error) { } catch (error) {
isAlive = false; isAlive = false;
const statusCode = error.response?.status || this.NETWORK_ERROR; const statusCode = error.response?.status || this.NETWORK_ERROR;
const message = http.STATUS_CODES[statusCode] || "Network Error"; const message = http.STATUS_CODES[statusCode] || "Network Error";
const checkData = { const checkData = {
monitorId: job.data._id, monitorId: job.data._id,
status: isAlive, status: isAlive,
statusCode, statusCode,
message, message,
accessibility: 0, accessibility: 0,
bestPractices: 0, bestPractices: 0,
seo: 0, seo: 0,
performance: 0, performance: 0,
}; };
this.logAndStoreCheck(checkData, this.db.createPageSpeedCheck); this.logAndStoreCheck(checkData, this.db.createPageSpeedCheck);
} finally { } finally {
this.handleStatusUpdate(job, isAlive); this.handleStatusUpdate(job, isAlive);
} }
} }
/** /**
* Retrieves the status of a given job based on its type. * Retrieves the status of a given job based on its type.
* For unsupported job types, it logs an error and returns false. * For unsupported job types, it logs an error and returns false.
* *
* @param {Object} job - The job object containing data necessary for processing. * @param {Object} job - The job object containing data necessary for processing.
* @returns {Promise<boolean>} The status of the job if it is supported and processed successfully, otherwise false. * @returns {Promise<boolean>} The status of the job if it is supported and processed successfully, otherwise false.
*/ */
async getStatus(job) { async getStatus(job) {
switch (job.data.type) { switch (job.data.type) {
case this.TYPE_PING: case this.TYPE_PING:
return await this.handlePing(job); return await this.handlePing(job);
case this.TYPE_HTTP: case this.TYPE_HTTP:
return await this.handleHttp(job); return await this.handleHttp(job);
case this.TYPE_PAGESPEED: case this.TYPE_PAGESPEED:
return await this.handlePagespeed(job); return await this.handlePagespeed(job);
default: default:
logger.error(`Unsupported type: ${job.data.type}`, { logger.error(`Unsupported type: ${job.data.type}`, {
service: this.SERVICE_NAME, service: this.SERVICE_NAME,
method: "getStatus", method: "getStatus",
jobId: job.id, jobId: job.id,
}); });
return false; return false;
} }
} }
/** /**
* Logs and stores the result of a check for a specific job. * Logs and stores the result of a check for a specific job.
* *
* @param {Object} data - Data to be written * @param {Object} data - Data to be written
* @param {function} writeToDB - DB write method * @param {function} writeToDB - DB write method
* *
* @returns {Promise<boolean>} The status of the inserted check if successful, otherwise false. * @returns {Promise<boolean>} The status of the inserted check if successful, otherwise false.
*/ */
async logAndStoreCheck(data, writeToDB) { async logAndStoreCheck(data, writeToDB) {
try { try {
const insertedCheck = await writeToDB(data); const insertedCheck = await writeToDB(data);
if (insertedCheck !== null && insertedCheck !== undefined) { if (insertedCheck !== null && insertedCheck !== undefined) {
return insertedCheck.status; return insertedCheck.status;
} }
} catch (error) { } catch (error) {
logger.error(`Error wrtiting check for ${data.monitorId}`, { logger.error(`Error wrtiting check for ${data.monitorId}`, {
service: this.SERVICE_NAME, service: this.SERVICE_NAME,
method: "logAndStoreCheck", method: "logAndStoreCheck",
monitorId: data.monitorId, monitorId: data.monitorId,
error: error, error: error,
}); });
} }
} }
} }
export default NetworkService; export default NetworkService;
+68 -68
View File
@@ -1,22 +1,22 @@
import AppSettings from "../db/models/AppSettings.js"; import AppSettings from "../db/models/AppSettings.js";
const SERVICE_NAME = "SettingsService"; const SERVICE_NAME = "SettingsService";
const envConfig = { const envConfig = {
logLevel: undefined, logLevel: undefined,
apiBaseUrl: undefined, apiBaseUrl: undefined,
clientHost: process.env.CLIENT_HOST, clientHost: process.env.CLIENT_HOST,
jwtSecret: process.env.JWT_SECRET, jwtSecret: process.env.JWT_SECRET,
refreshTokenSecret: process.env.REFRESH_TOKEN_SECRET, refreshTokenSecret: process.env.REFRESH_TOKEN_SECRET,
dbType: process.env.DB_TYPE, dbType: process.env.DB_TYPE,
dbConnectionString: process.env.DB_CONNECTION_STRING, dbConnectionString: process.env.DB_CONNECTION_STRING,
redisHost: process.env.REDIS_HOST, redisHost: process.env.REDIS_HOST,
redisPort: process.env.REDIS_PORT, redisPort: process.env.REDIS_PORT,
jwtTTL: process.env.TOKEN_TTL, jwtTTL: process.env.TOKEN_TTL,
refreshTokenTTL: process.env.REFRESH_TOKEN_TTL, refreshTokenTTL: process.env.REFRESH_TOKEN_TTL,
pagespeedApiKey: process.env.PAGESPEED_API_KEY, pagespeedApiKey: process.env.PAGESPEED_API_KEY,
systemEmailHost: process.env.SYSTEM_EMAIL_HOST, systemEmailHost: process.env.SYSTEM_EMAIL_HOST,
systemEmailPort: process.env.SYSTEM_EMAIL_PORT, systemEmailPort: process.env.SYSTEM_EMAIL_PORT,
systemEmailAddress: process.env.SYSTEM_EMAIL_ADDRESS, systemEmailAddress: process.env.SYSTEM_EMAIL_ADDRESS,
systemEmailPassword: process.env.SYSTEM_EMAIL_PASSWORD, systemEmailPassword: process.env.SYSTEM_EMAIL_PASSWORD,
}; };
/** /**
* SettingsService * SettingsService
@@ -26,60 +26,60 @@ const envConfig = {
* from the database if they are not set in the environment. * from the database if they are not set in the environment.
*/ */
class SettingsService { class SettingsService {
/** /**
* Constructs a new SettingsService * Constructs a new SettingsService
* @constructor * @constructor
* @throws {Error} * @throws {Error}
*/ constructor() { */ constructor() {
this.settings = { ...envConfig }; this.settings = { ...envConfig };
} }
/** /**
* Load settings from the database and merge with environment settings. * Load settings from the database and merge with environment settings.
* If there are any settings that weren't set by environment variables, use user settings from the database. * If there are any settings that weren't set by environment variables, use user settings from the database.
* @returns {Promise<Object>} The merged settings. * @returns {Promise<Object>} The merged settings.
* @throws Will throw an error if settings are not found in the database or if settings have not been loaded. * @throws Will throw an error if settings are not found in the database or if settings have not been loaded.
*/ async loadSettings() { */ async loadSettings() {
try { try {
const dbSettings = await AppSettings.findOne(); const dbSettings = await AppSettings.findOne();
if (!this.settings) { if (!this.settings) {
throw new Error("Settings not found"); throw new Error("Settings not found");
} }
// If there are any settings that weren't set by environment variables, use user settings from DB // If there are any settings that weren't set by environment variables, use user settings from DB
for (const key in envConfig) { for (const key in envConfig) {
if (envConfig[key] === undefined && dbSettings[key] !== undefined) { if (envConfig[key] === undefined && dbSettings[key] !== undefined) {
this.settings[key] = dbSettings[key]; this.settings[key] = dbSettings[key];
} }
} }
if (!this.settings) { if (!this.settings) {
throw new Error("Settings not found"); throw new Error("Settings not found");
} }
return this.settings; return this.settings;
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "loadSettings") : null; error.method === undefined ? (error.method = "loadSettings") : null;
throw error; throw error;
} }
} }
/** /**
* Reload settings by calling loadSettings. * Reload settings by calling loadSettings.
* @returns {Promise<Object>} The reloaded settings. * @returns {Promise<Object>} The reloaded settings.
*/ */
async reloadSettings() { async reloadSettings() {
return this.loadSettings(); return this.loadSettings();
} }
/** /**
* Get the current settings. * Get the current settings.
* @returns {Object} The current settings. * @returns {Object} The current settings.
* @throws Will throw an error if settings have not been loaded. * @throws Will throw an error if settings have not been loaded.
*/ */
getSettings() { getSettings() {
if (!this.settings) { if (!this.settings) {
throw new Error("Settings have not been loaded"); throw new Error("Settings have not been loaded");
} }
return this.settings; return this.settings;
} }
} }
export default SettingsService; export default SettingsService;
+49 -32
View File
@@ -1,35 +1,52 @@
<!-- name, link --> <!-- name, link -->
<mjml> <mjml>
<mj-head> <mj-head>
<mj-font name="Roboto" href="https://fonts.googleapis.com/css?family=Roboto:300,500"></mj-font> <mj-font
<mj-attributes> name="Roboto"
<mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all> href="https://fonts.googleapis.com/css?family=Roboto:300,500"
<mj-text font-weight="300" font-size="16px" color="#616161" line-height="24px"></mj-text> ></mj-font>
<mj-section padding="0px"></mj-section> <mj-attributes>
</mj-attributes> <mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all>
</mj-head> <mj-text
<mj-body> font-weight="300"
<mj-section padding="20px 0"> font-size="16px"
<mj-column width="100%"> color="#616161"
<mj-text align="left" font-size="10px">Message from BlueWave Uptime Service</mj-text> line-height="24px"
</mj-column> ></mj-text>
</mj-section> <mj-section padding="0px"></mj-section>
<mj-section> </mj-attributes>
<mj-column width="100%"> </mj-head>
<mj-text> <mj-body>
<p>Hello {{name}}!</p> <mj-section padding="20px 0">
<p>One of the admins created an account for you on the BlueWave Uptime server.</p> <mj-column width="100%">
<p>You can go ahead and create your account using this link.</p> <mj-text
<p><a href={{link}}>{{link}}</a></p> align="left"
<p>Thank you.</p> font-size="10px"
</mj-text> >Message from BlueWave Uptime Service</mj-text
</mj-column> >
<mj-column width="100%"> </mj-column>
<mj-divider border-width="1px" border-color="#E0E0E0"></mj-divider> </mj-section>
<mj-text font-size="12px"> <mj-section>
<p>This email was sent by BlueWave Uptime.</p> <mj-column width="100%">
</mj-text> <mj-text>
</mj-column> <p>Hello {{name}}!</p>
</mj-section> <p>
</mj-body> One of the admins created an account for you on the BlueWave Uptime server.
</p>
<p>You can go ahead and create your account using this link.</p>
<p><a href="{{link}}">{{link}}</a></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 BlueWave Uptime.</p>
</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml> </mjml>
+64 -36
View File
@@ -1,38 +1,66 @@
<mjml> <mjml>
<mj-head> <mj-head>
<mj-font name="Roboto" href="https://fonts.googleapis.com/css?family=Roboto:300,500"></mj-font> <mj-font
<mj-attributes> name="Roboto"
<mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all> href="https://fonts.googleapis.com/css?family=Roboto:300,500"
<mj-text font-weight="300" font-size="16px" color="#616161" line-height="24px"></mj-text> ></mj-font>
<mj-section padding="0px"></mj-section> <mj-attributes>
</mj-attributes> <mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all>
</mj-head> <mj-text
<mj-body> font-weight="300"
<mj-section padding="20px 0"> font-size="16px"
<mj-column width="100%"> color="#616161"
<mj-text align="left" font-size="10px">Message from BlueWave Uptime Service</mj-text> line-height="24px"
</mj-column> ></mj-text>
<mj-column width="45%" padding-top="20px"> <mj-section padding="0px"></mj-section>
<mj-text align="center" font-weight="500" padding="0px" font-size="18px" color="green">No incidents this week!</mj-text> </mj-attributes>
<mj-divider border-width="2px" border-color="#616161"></mj-divider> </mj-head>
</mj-column> <mj-body>
</mj-section> <mj-section padding="20px 0">
<mj-section> <mj-column width="100%">
<mj-column width="100%"> <mj-text
<mj-text> align="left"
<p>Hello {{name}}!</p> font-size="10px"
<p>There were no incidents this week. Good job!</p> >Message from BlueWave Uptime Service</mj-text
<p><b>Current monitors:</b></p> >
<p><b>Google:</b> 100% availability</p> </mj-column>
<p><b>Canada.ca:</b>100% availability</p> <mj-column
</mj-text> width="45%"
</mj-column> padding-top="20px"
<mj-column width="100%"> >
<mj-divider border-width="1px" border-color="#E0E0E0"></mj-divider> <mj-text
<mj-text font-size="12px"> align="center"
<p>This email was sent by BlueWave Uptime.</p> font-weight="500"
</mj-text> padding="0px"
</mj-column> font-size="18px"
</mj-section> color="green"
</mj-body> >No incidents this week!</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>There were no incidents this week. Good job!</p>
<p><b>Current monitors:</b></p>
<p><b>Google:</b> 100% availability</p>
<p><b>Canada.ca:</b>100% availability</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 BlueWave Uptime.</p>
</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml> </mjml>
+51 -38
View File
@@ -1,43 +1,56 @@
<!-- name, email, url --> <!-- name, email, url -->
<mjml> <mjml>
<mj-head> <mj-head>
<mj-font name="Roboto" href="https://fonts.googleapis.com/css?family=Roboto:300,500"></mj-font> <mj-font
<mj-attributes> name="Roboto"
<mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all> href="https://fonts.googleapis.com/css?family=Roboto:300,500"
<mj-text font-weight="300" font-size="16px" color="#616161" line-height="24px"></mj-text> ></mj-font>
<mj-section padding="0px"></mj-section> <mj-attributes>
</mj-attributes> <mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all>
</mj-head> <mj-text
<mj-body> font-weight="300"
<mj-section padding="20px 0"> font-size="16px"
<mj-column width="100%"> color="#616161"
<mj-text align="left" font-size="10px"> line-height="24px"
Message from BlueWave Uptime Service ></mj-text>
</mj-text> <mj-section padding="0px"></mj-section>
</mj-column> </mj-attributes>
</mj-section> </mj-head>
<mj-section> <mj-body>
<mj-column width="100%"> <mj-section padding="20px 0">
<mj-text> <mj-column width="100%">
<p>Hello {{name}}!</p> <mj-text
<p> align="left"
You are receiving this email because a password reset request font-size="10px"
has been made for {{email}}. Please use the >
link below on the site to reset your password. Message from BlueWave Uptime Service
</p> </mj-text>
<a href="{{url}}">Reset Password</a> </mj-column>
<p>If you didn't request this, please ignore this email.</p> </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> <p>Thank you.</p>
</mj-text> </mj-text>
</mj-column> </mj-column>
<mj-column width="100%"> <mj-column width="100%">
<mj-divider border-width="1px" border-color="#E0E0E0"></mj-divider> <mj-divider
<mj-text font-size="12px"> border-width="1px"
<p>This email was sent by BlueWave Uptime.</p> border-color="#E0E0E0"
</mj-text> ></mj-divider>
</mj-column> <mj-text font-size="12px">
</mj-section> <p>This email was sent by BlueWave Uptime.</p>
</mj-body> </mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml> </mjml>
+71 -55
View File
@@ -1,57 +1,73 @@
<mjml> <mjml>
<mj-head> <mj-head>
<mj-font name="Roboto" href="https://fonts.googleapis.com/css?family=Roboto:300,500"></mj-font> <mj-font
<mj-attributes> name="Roboto"
<mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all> href="https://fonts.googleapis.com/css?family=Roboto:300,500"
<mj-text font-weight="300" font-size="16px" color="#616161" line-height="24px"></mj-text> ></mj-font>
<mj-section padding="0px"></mj-section> <mj-attributes>
</mj-attributes> <mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all>
</mj-head> <mj-text
<mj-body> font-weight="300"
<mj-section padding="20px 0"> font-size="16px"
<mj-column width="100%"> color="#616161"
<mj-text align="left" font-size="10px"> line-height="24px"
Message from BlueWave Uptime Service ></mj-text>
</mj-text> <mj-section padding="0px"></mj-section>
</mj-column> </mj-attributes>
<mj-column width="45%" padding-top="20px"> </mj-head>
<mj-text align="center" font-weight="500" padding="0px" font-size="18px" color="red"> <mj-body>
Google.com is down <mj-section padding="20px 0">
</mj-text> <mj-column width="100%">
<mj-divider border-width="2px" border-color="#616161"></mj-divider> <mj-text
</mj-column> align="left"
</mj-section> font-size="10px"
<mj-section> >
<mj-column width="100%"> Message from BlueWave Uptime Service
<mj-text> </mj-text>
<p>Hello {{name}}!</p> </mj-column>
<p> <mj-column
We detected an incident on one of your monitors. Your service is width="45%"
currently down. We'll send a message to you once it is up again. padding-top="20px"
</p> >
<p> <mj-text
<b>Monitor name:</b> {{monitor}} align="center"
</p> font-weight="500"
<p> padding="0px"
<b>URL:</b> {{url}} font-size="18px"
</p> color="red"
<p> >
<b>Problem:</b> {{problem}} Google.com is down
</p> </mj-text>
<p> <mj-divider
<b>Start date:</b> {{startDate}} border-width="2px"
</p> border-color="#616161"
</mj-text> ></mj-divider>
</mj-column> </mj-column>
<mj-column width="100%"> </mj-section>
<mj-divider border-width="1px" border-color="#E0E0E0"></mj-divider> <mj-section>
<mj-button background-color="#1570EF"> <mj-column width="100%">
View incident details <mj-text>
</mj-button> <p>Hello {{name}}!</p>
<mj-text font-size="12px"> <p>
<p>This email was sent by BlueWave Uptime.</p> We detected an incident on one of your monitors. Your service is currently
</mj-text> down. We'll send a message to you once it is up again.
</mj-column> </p>
</mj-section> <p><b>Monitor name:</b> {{monitor}}</p>
</mj-body> <p><b>URL:</b> {{url}}</p>
<p><b>Problem:</b> {{problem}}</p>
<p><b>Start date:</b> {{startDate}}</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 BlueWave Uptime.</p>
</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml> </mjml>
+70 -61
View File
@@ -1,63 +1,72 @@
<mjml> <mjml>
<mj-head> <mj-head>
<mj-font name="Roboto" href="https://fonts.googleapis.com/css?family=Roboto:300,500"></mj-font> <mj-font
<mj-attributes> name="Roboto"
<mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all> href="https://fonts.googleapis.com/css?family=Roboto:300,500"
<mj-text font-weight="300" font-size="16px" color="#616161" line-height="24px"></mj-text> ></mj-font>
<mj-section padding="0px"></mj-section> <mj-attributes>
</mj-attributes> <mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all>
</mj-head> <mj-text
<mj-body> font-weight="300"
<mj-section padding="20px 0"> font-size="16px"
<mj-column width="100%"> color="#616161"
<mj-text align="left" font-size="10px"> line-height="24px"
Message from BlueWave Uptime Service ></mj-text>
</mj-text> <mj-section padding="0px"></mj-section>
</mj-column> </mj-attributes>
<mj-column width="45%" padding-top="20px"> </mj-head>
<mj-text align="center" font-weight="500" padding="0px" font-size="18px" color="green"> <mj-body>
{{monitor}} is up <mj-section padding="20px 0">
</mj-text> <mj-column width="100%">
<mj-divider border-width="2px" border-color="#616161"></mj-divider> <mj-text
</mj-column> align="left"
</mj-section> font-size="10px"
<mj-section> >
<mj-column width="100%"> Message from BlueWave Uptime Service
<mj-text> </mj-text>
<p>Hello {{name}}!</p> </mj-column>
<p> <mj-column
Your latest incident is resolved and your monitored service is width="45%"
up again. padding-top="20px"
</p> >
<p> <mj-text
<b>Monitor name:</b> {{monitor}} align="center"
</p> font-weight="500"
<p> padding="0px"
<b>URL:</b> {{url}} font-size="18px"
</p> color="green"
<p> >
<b>Problem:</b> {{problem}} {{monitor}} is up
</p> </mj-text>
<p> <mj-divider
<b>Start date:</b> {{startDate}} border-width="2px"
</p> border-color="#616161"
<p> ></mj-divider>
<b>Resolved date:</b> {{resolvedDate}} </mj-column>
</p> </mj-section>
<p> <mj-section>
<b>Duration:</b>{{duration}} <mj-column width="100%">
</p> <mj-text>
</mj-text> <p>Hello {{name}}!</p>
</mj-column> <p>Your latest incident is resolved and your monitored service is up again.</p>
<mj-column width="100%"> <p><b>Monitor name:</b> {{monitor}}</p>
<mj-divider border-width="1px" border-color="#E0E0E0"></mj-divider> <p><b>URL:</b> {{url}}</p>
<mj-button background-color="#1570EF"> <p><b>Problem:</b> {{problem}}</p>
View incident details <p><b>Start date:</b> {{startDate}}</p>
</mj-button> <p><b>Resolved date:</b> {{resolvedDate}}</p>
<mj-text font-size="12px"> <p><b>Duration:</b>{{duration}}</p>
<p>This email was sent by BlueWave Uptime.</p> </mj-text>
</mj-text> </mj-column>
</mj-column> <mj-column width="100%">
</mj-section> <mj-divider
</mj-body> 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 BlueWave Uptime.</p>
</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml> </mjml>
+54 -41
View File
@@ -1,44 +1,57 @@
<!-- name --> <!-- name -->
<mjml> <mjml>
<mj-head> <mj-head>
<mj-font name="Roboto" href="https://fonts.googleapis.com/css?family=Roboto:300,500"></mj-font> <mj-font
<mj-attributes> name="Roboto"
<mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all> href="https://fonts.googleapis.com/css?family=Roboto:300,500"
<mj-text font-weight="300" font-size="16px" color="#616161" line-height="24px"></mj-text> ></mj-font>
<mj-section padding="0px"></mj-section> <mj-attributes>
</mj-attributes> <mj-all font-family="Roboto, Helvetica, sans-serif"></mj-all>
</mj-head> <mj-text
<mj-body> font-weight="300"
<mj-section padding="20px 0"> font-size="16px"
<mj-column width="100%"> color="#616161"
<mj-text align="left" font-size="10px"> line-height="24px"
Message from BlueWave Uptime Service ></mj-text>
</mj-text> <mj-section padding="0px"></mj-section>
</mj-column> </mj-attributes>
</mj-section> </mj-head>
<mj-section> <mj-body>
<mj-column width="100%"> <mj-section padding="20px 0">
<mj-text> <mj-column width="100%">
<p>Hello {{name}}!</p> <mj-text
<p> align="left"
Thank you for trying out BlueWave Uptime! We developed it with font-size="10px"
great care to meet our own needs, and we're excited to share it >
with you. Message from BlueWave Uptime Service
</p> </mj-text>
<p> </mj-column>
BlueWave Uptime is an automated way of checking whether a </mj-section>
service such as a website or an application is available or not. <mj-section>
</p> <mj-column width="100%">
<p>We hope you find our service as valuable as we do.</p> <mj-text>
<p>Thank you.</p> <p>Hello {{name}}!</p>
</mj-text> <p>
</mj-column> Thank you for trying out BlueWave Uptime! We developed it with great care to
<mj-column width="100%"> meet our own needs, and we're excited to share it with you.
<mj-divider border-width="1px" border-color="#E0E0E0"></mj-divider> </p>
<mj-text font-size="12px"> <p>
<p>This email was sent by BlueWave Uptime.</p> BlueWave Uptime is an automated way of checking whether a service such as a
</mj-text> website or an application is available or not.
</mj-column> </p>
</mj-section> <p>We hope you find our service as valuable as we do.</p>
</mj-body> <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 BlueWave Uptime.</p>
</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml> </mjml>
+323 -325
View File
@@ -1,375 +1,373 @@
import { import {
createCheck, createCheck,
getChecks, getChecks,
getTeamChecks, getTeamChecks,
deleteChecks, deleteChecks,
deleteChecksByTeamId, deleteChecksByTeamId,
updateChecksTTL, updateChecksTTL,
} from "../../controllers/checkController.js"; } from "../../controllers/checkController.js";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import { errorMessages, successMessages } from "../../utils/messages.js"; import { errorMessages, successMessages } from "../../utils/messages.js";
import sinon from "sinon"; import sinon from "sinon";
describe("Check Controller - createCheck", () => { describe("Check Controller - createCheck", () => {
let req, res, next, handleError; let req, res, next, handleError;
beforeEach(() => { beforeEach(() => {
req = { req = {
params: {}, params: {},
body: {}, body: {},
db: { db: {
createCheck: sinon.stub(), createCheck: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
handleError = sinon.stub(); handleError = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); // Restore the original methods after each test sinon.restore(); // Restore the original methods after each test
}); });
it("should reject with a validation if params are invalid", async () => { it("should reject with a validation if params are invalid", async () => {
await createCheck(req, res, next); await createCheck(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with a validation error if body is invalid", async () => { it("should reject with a validation error if body is invalid", async () => {
req.params = { req.params = {
monitorId: "monitorId", monitorId: "monitorId",
}; };
await createCheck(req, res, next); await createCheck(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should call next with error if data retrieval fails", async () => { it("should call next with error if data retrieval fails", async () => {
req.params = { req.params = {
monitorId: "monitorId", monitorId: "monitorId",
}; };
req.body = { req.body = {
monitorId: "monitorId", monitorId: "monitorId",
status: true, status: true,
responseTime: 100, responseTime: 100,
statusCode: 200, statusCode: 200,
message: "message", message: "message",
}; };
req.db.createCheck.rejects(new Error("error")); req.db.createCheck.rejects(new Error("error"));
await createCheck(req, res, next); await createCheck(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
}); });
it("should return a success message if check is created", async () => { it("should return a success message if check is created", async () => {
req.params = { req.params = {
monitorId: "monitorId", monitorId: "monitorId",
}; };
req.db.createCheck.resolves({ id: "123" }); req.db.createCheck.resolves({ id: "123" });
req.body = { req.body = {
monitorId: "monitorId", monitorId: "monitorId",
status: true, status: true,
responseTime: 100, responseTime: 100,
statusCode: 200, statusCode: 200,
message: "message", message: "message",
}; };
await createCheck(req, res, next); await createCheck(req, res, next);
expect(res.status.calledWith(200)).to.be.true; expect(res.status.calledWith(200)).to.be.true;
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: successMessages.CHECK_CREATE, msg: successMessages.CHECK_CREATE,
data: { id: "123" }, data: { id: "123" },
}) })
).to.be.true; ).to.be.true;
expect(next.notCalled).to.be.true; expect(next.notCalled).to.be.true;
}); });
}); });
describe("Check Controller - getChecks", () => { describe("Check Controller - getChecks", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
params: {}, params: {},
query: {}, query: {},
db: { db: {
getChecks: sinon.stub(), getChecks: sinon.stub(),
getChecksCount: sinon.stub(), getChecksCount: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject with a validation error if params are invalid", async () => { it("should reject with a validation error if params are invalid", async () => {
await getChecks(req, res, next); await getChecks(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should return a success message if checks are found", async () => { it("should return a success message if checks are found", async () => {
req.params = { req.params = {
monitorId: "monitorId", monitorId: "monitorId",
}; };
req.db.getChecks.resolves([{ id: "123" }]); req.db.getChecks.resolves([{ id: "123" }]);
req.db.getChecksCount.resolves(1); req.db.getChecksCount.resolves(1);
await getChecks(req, res, next); await getChecks(req, res, next);
expect(res.status.calledWith(200)).to.be.true; expect(res.status.calledWith(200)).to.be.true;
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: successMessages.CHECK_GET, msg: successMessages.CHECK_GET,
data: { checksCount: 1, checks: [{ id: "123" }] }, data: { checksCount: 1, checks: [{ id: "123" }] },
}) })
).to.be.true; ).to.be.true;
expect(next.notCalled).to.be.true; expect(next.notCalled).to.be.true;
}); });
it("should call next with error if data retrieval fails", async () => { it("should call next with error if data retrieval fails", async () => {
req.params = { req.params = {
monitorId: "monitorId", monitorId: "monitorId",
}; };
req.db.getChecks.rejects(new Error("error")); req.db.getChecks.rejects(new Error("error"));
await getChecks(req, res, next); await getChecks(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
}); });
}); });
describe("Check Controller - getTeamChecks", () => { describe("Check Controller - getTeamChecks", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
params: {}, params: {},
query: {}, query: {},
db: { db: {
getTeamChecks: sinon.stub(), getTeamChecks: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject with a validation error if params are invalid", async () => { it("should reject with a validation error if params are invalid", async () => {
await getTeamChecks(req, res, next); await getTeamChecks(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should return 200 and check data on successful validation and data retrieval", async () => { it("should return 200 and check data on successful validation and data retrieval", async () => {
req.params = { teamId: "1" }; req.params = { teamId: "1" };
const checkData = [{ id: 1, name: "Check 1" }]; const checkData = [{ id: 1, name: "Check 1" }];
req.db.getTeamChecks.resolves(checkData); req.db.getTeamChecks.resolves(checkData);
await getTeamChecks(req, res, next); await getTeamChecks(req, res, next);
expect(req.db.getTeamChecks.calledOnceWith(req)).to.be.true; expect(req.db.getTeamChecks.calledOnceWith(req)).to.be.true;
expect(res.status.calledOnceWith(200)).to.be.true; expect(res.status.calledOnceWith(200)).to.be.true;
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.CHECK_GET, msg: successMessages.CHECK_GET,
data: checkData, data: checkData,
}) })
).to.be.true; ).to.be.true;
}); });
it("should call next with error if data retrieval fails", async () => { it("should call next with error if data retrieval fails", async () => {
req.params = { teamId: "1" }; req.params = { teamId: "1" };
req.db.getTeamChecks.rejects(new Error("Retrieval Error")); req.db.getTeamChecks.rejects(new Error("Retrieval Error"));
await getTeamChecks(req, res, next); await getTeamChecks(req, res, next);
expect(req.db.getTeamChecks.calledOnceWith(req)).to.be.true; expect(req.db.getTeamChecks.calledOnceWith(req)).to.be.true;
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(res.status.notCalled).to.be.true; expect(res.status.notCalled).to.be.true;
expect(res.json.notCalled).to.be.true; expect(res.json.notCalled).to.be.true;
}); });
}); });
describe("Check Controller - deleteChecks", () => { describe("Check Controller - deleteChecks", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
params: {}, params: {},
db: { db: {
deleteChecks: sinon.stub(), deleteChecks: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if param validation fails", async () => { it("should reject with an error if param validation fails", async () => {
await deleteChecks(req, res, next); await deleteChecks(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should call next with error if data retrieval fails", async () => { it("should call next with error if data retrieval fails", async () => {
req.params = { monitorId: "1" }; req.params = { monitorId: "1" };
req.db.deleteChecks.rejects(new Error("Deletion Error")); req.db.deleteChecks.rejects(new Error("Deletion Error"));
await deleteChecks(req, res, next); await deleteChecks(req, res, next);
expect(req.db.deleteChecks.calledOnceWith(req.params.monitorId)).to.be.true; expect(req.db.deleteChecks.calledOnceWith(req.params.monitorId)).to.be.true;
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(res.status.notCalled).to.be.true; expect(res.status.notCalled).to.be.true;
expect(res.json.notCalled).to.be.true; expect(res.json.notCalled).to.be.true;
}); });
it("should delete checks successfully", async () => { it("should delete checks successfully", async () => {
req.params = { monitorId: "123" }; req.params = { monitorId: "123" };
req.db.deleteChecks.resolves(1); req.db.deleteChecks.resolves(1);
await deleteChecks(req, res, next); await deleteChecks(req, res, next);
expect(req.db.deleteChecks.calledOnceWith(req.params.monitorId)).to.be.true; expect(req.db.deleteChecks.calledOnceWith(req.params.monitorId)).to.be.true;
expect(res.status.calledOnceWith(200)).to.be.true; expect(res.status.calledOnceWith(200)).to.be.true;
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.CHECK_DELETE, msg: successMessages.CHECK_DELETE,
data: { deletedCount: 1 }, data: { deletedCount: 1 },
}) })
).to.be.true; ).to.be.true;
}); });
}); });
describe("Check Controller - deleteChecksByTeamId", () => { describe("Check Controller - deleteChecksByTeamId", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
params: {}, params: {},
db: { db: {
deleteChecksByTeamId: sinon.stub(), deleteChecksByTeamId: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if param validation fails", async () => { it("should reject with an error if param validation fails", async () => {
await deleteChecksByTeamId(req, res, next); await deleteChecksByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should call next with error if data retrieval fails", async () => { it("should call next with error if data retrieval fails", async () => {
req.params = { teamId: "1" }; req.params = { teamId: "1" };
req.db.deleteChecksByTeamId.rejects(new Error("Deletion Error")); req.db.deleteChecksByTeamId.rejects(new Error("Deletion Error"));
await deleteChecksByTeamId(req, res, next); await deleteChecksByTeamId(req, res, next);
expect(req.db.deleteChecksByTeamId.calledOnceWith(req.params.teamId)).to.be expect(req.db.deleteChecksByTeamId.calledOnceWith(req.params.teamId)).to.be.true;
.true; expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0]).to.be.an("error"); expect(res.status.notCalled).to.be.true;
expect(res.status.notCalled).to.be.true; expect(res.json.notCalled).to.be.true;
expect(res.json.notCalled).to.be.true; });
});
it("should delete checks successfully", async () => { it("should delete checks successfully", async () => {
req.params = { teamId: "123" }; req.params = { teamId: "123" };
req.db.deleteChecksByTeamId.resolves(1); req.db.deleteChecksByTeamId.resolves(1);
await deleteChecksByTeamId(req, res, next); await deleteChecksByTeamId(req, res, next);
expect(req.db.deleteChecksByTeamId.calledOnceWith(req.params.teamId)).to.be expect(req.db.deleteChecksByTeamId.calledOnceWith(req.params.teamId)).to.be.true;
.true; expect(res.status.calledOnceWith(200)).to.be.true;
expect(res.status.calledOnceWith(200)).to.be.true; expect(
expect( res.json.calledOnceWith({
res.json.calledOnceWith({ success: true,
success: true, msg: successMessages.CHECK_DELETE,
msg: successMessages.CHECK_DELETE, data: { deletedCount: 1 },
data: { deletedCount: 1 }, })
}) ).to.be.true;
).to.be.true; });
});
}); });
describe("Check Controller - updateCheckTTL", () => { describe("Check Controller - updateCheckTTL", () => {
let stub, req, res, next; let stub, req, res, next;
beforeEach(() => { beforeEach(() => {
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
}); });
req = { req = {
body: {}, body: {},
headers: { authorization: "Bearer token" }, headers: { authorization: "Bearer token" },
settingsService: { settingsService: {
getSettings: sinon.stub().returns({ jwtSecret: "my_secret" }), getSettings: sinon.stub().returns({ jwtSecret: "my_secret" }),
}, },
db: { db: {
updateChecksTTL: sinon.stub(), updateChecksTTL: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
stub.restore(); stub.restore();
}); });
it("should reject if body validation fails", async () => { it("should reject if body validation fails", async () => {
await updateChecksTTL(req, res, next); await updateChecksTTL(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should throw a JwtError if verification fails", async () => { it("should throw a JwtError if verification fails", async () => {
stub.restore(); stub.restore();
req.body = { req.body = {
ttl: 1, ttl: 1,
}; };
await updateChecksTTL(req, res, next); await updateChecksTTL(req, res, next);
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError); expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
}); });
it("should call next with error if data retrieval fails", async () => { it("should call next with error if data retrieval fails", async () => {
req.body = { req.body = {
ttl: 1, ttl: 1,
}; };
req.db.updateChecksTTL.rejects(new Error("Update Error")); req.db.updateChecksTTL.rejects(new Error("Update Error"));
await updateChecksTTL(req, res, next); await updateChecksTTL(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
}); });
it("should update TTL successfully", async () => { it("should update TTL successfully", async () => {
req.body = { req.body = {
ttl: 1, ttl: 1,
}; };
req.db.updateChecksTTL.resolves(); req.db.updateChecksTTL.resolves();
await updateChecksTTL(req, res, next); await updateChecksTTL(req, res, next);
expect(req.db.updateChecksTTL.calledOnceWith("123", 1 * 86400)).to.be.true; expect(req.db.updateChecksTTL.calledOnceWith("123", 1 * 86400)).to.be.true;
expect(res.status.calledOnceWith(200)).to.be.true; expect(res.status.calledOnceWith(200)).to.be.true;
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.CHECK_UPDATE_TTL, msg: successMessages.CHECK_UPDATE_TTL,
}) })
).to.be.true; ).to.be.true;
}); });
}); });
+178 -178
View File
@@ -1,203 +1,203 @@
import { import {
issueInvitation, issueInvitation,
inviteVerifyController, inviteVerifyController,
} from "../../controllers/inviteController.js"; } from "../../controllers/inviteController.js";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import sinon from "sinon"; import sinon from "sinon";
import joi from "joi"; import joi from "joi";
describe("inviteController - issueInvitation", () => { describe("inviteController - issueInvitation", () => {
let req, res, next, stub; let req, res, next, stub;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: { authorization: "Bearer token" }, headers: { authorization: "Bearer token" },
body: { body: {
email: "test@test.com", email: "test@test.com",
role: ["admin"], role: ["admin"],
teamId: "123", teamId: "123",
}, },
db: { requestInviteToken: sinon.stub() }, db: { requestInviteToken: sinon.stub() },
settingsService: { getSettings: sinon.stub() }, settingsService: { getSettings: sinon.stub() },
emailService: { buildAndSendEmail: sinon.stub() }, emailService: { buildAndSendEmail: sinon.stub() },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if role validation fails", async () => { it("should reject with an error if role validation fails", async () => {
stub = sinon.stub(jwt, "decode").callsFake(() => { stub = sinon.stub(jwt, "decode").callsFake(() => {
return { role: ["bad_role"], firstname: "first_name", teamId: "1" }; return { role: ["bad_role"], firstname: "first_name", teamId: "1" };
}); });
await issueInvitation(req, res, next); await issueInvitation(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0]).to.be.instanceOf(joi.ValidationError); expect(next.firstCall.args[0]).to.be.instanceOf(joi.ValidationError);
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
stub.restore(); stub.restore();
}); });
it("should reject with an error if body validation fails", async () => { it("should reject with an error if body validation fails", async () => {
stub = sinon.stub(jwt, "decode").callsFake(() => { stub = sinon.stub(jwt, "decode").callsFake(() => {
return { role: ["admin"], firstname: "first_name", teamId: "1" }; return { role: ["admin"], firstname: "first_name", teamId: "1" };
}); });
req.body = {}; req.body = {};
await issueInvitation(req, res, next); await issueInvitation(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
stub.restore(); stub.restore();
}); });
it("should reject with an error if DB operations fail", async () => { it("should reject with an error if DB operations fail", async () => {
stub = sinon.stub(jwt, "decode").callsFake(() => { stub = sinon.stub(jwt, "decode").callsFake(() => {
return { role: ["admin"], firstname: "first_name", teamId: "1" }; return { role: ["admin"], firstname: "first_name", teamId: "1" };
}); });
req.db.requestInviteToken.throws(new Error("DB error")); req.db.requestInviteToken.throws(new Error("DB error"));
await issueInvitation(req, res, next); await issueInvitation(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error"); expect(next.firstCall.args[0].message).to.equal("DB error");
stub.restore(); stub.restore();
}); });
it("should send an invite successfully", async () => { it("should send an invite successfully", async () => {
const token = "token"; const token = "token";
const decodedToken = { const decodedToken = {
role: "admin", role: "admin",
firstname: "John", firstname: "John",
teamId: "team123", teamId: "team123",
}; };
const inviteToken = { token: "inviteToken" }; const inviteToken = { token: "inviteToken" };
const clientHost = "http://localhost"; const clientHost = "http://localhost";
stub = sinon.stub(jwt, "decode").callsFake(() => { stub = sinon.stub(jwt, "decode").callsFake(() => {
return decodedToken; return decodedToken;
}); });
req.db.requestInviteToken.resolves(inviteToken); req.db.requestInviteToken.resolves(inviteToken);
req.settingsService.getSettings.returns({ clientHost }); req.settingsService.getSettings.returns({ clientHost });
req.emailService.buildAndSendEmail.resolves(); req.emailService.buildAndSendEmail.resolves();
await issueInvitation(req, res, next); await issueInvitation(req, res, next);
expect(res.status.calledWith(200)).to.be.true; expect(res.status.calledWith(200)).to.be.true;
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: "Invite sent", msg: "Invite sent",
data: inviteToken, data: inviteToken,
}) })
).to.be.true; ).to.be.true;
stub.restore(); stub.restore();
}); });
it("should send an email successfully", async () => { it("should send an email successfully", async () => {
const token = "token"; const token = "token";
const decodedToken = { const decodedToken = {
role: "admin", role: "admin",
firstname: "John", firstname: "John",
teamId: "team123", teamId: "team123",
}; };
const inviteToken = { token: "inviteToken" }; const inviteToken = { token: "inviteToken" };
const clientHost = "http://localhost"; const clientHost = "http://localhost";
stub = sinon.stub(jwt, "decode").callsFake(() => { stub = sinon.stub(jwt, "decode").callsFake(() => {
return decodedToken; return decodedToken;
}); });
req.db.requestInviteToken.resolves(inviteToken); req.db.requestInviteToken.resolves(inviteToken);
req.settingsService.getSettings.returns({ clientHost }); req.settingsService.getSettings.returns({ clientHost });
req.emailService.buildAndSendEmail.resolves(); req.emailService.buildAndSendEmail.resolves();
await issueInvitation(req, res, next); await issueInvitation(req, res, next);
expect(req.emailService.buildAndSendEmail.calledOnce).to.be.true; expect(req.emailService.buildAndSendEmail.calledOnce).to.be.true;
expect( expect(
req.emailService.buildAndSendEmail.calledWith( req.emailService.buildAndSendEmail.calledWith(
"employeeActivationTemplate", "employeeActivationTemplate",
{ {
name: "John", name: "John",
link: "http://localhost/register/inviteToken", link: "http://localhost/register/inviteToken",
}, },
"test@test.com", "test@test.com",
"Welcome to Uptime Monitor" "Welcome to Uptime Monitor"
) )
).to.be.true; ).to.be.true;
stub.restore(); stub.restore();
}); });
it("should continue executing if sending an email fails", async () => { it("should continue executing if sending an email fails", async () => {
const token = "token"; const token = "token";
req.emailService.buildAndSendEmail.rejects(new Error("Email error")); req.emailService.buildAndSendEmail.rejects(new Error("Email error"));
const decodedToken = { const decodedToken = {
role: "admin", role: "admin",
firstname: "John", firstname: "John",
teamId: "team123", teamId: "team123",
}; };
const inviteToken = { token: "inviteToken" }; const inviteToken = { token: "inviteToken" };
const clientHost = "http://localhost"; const clientHost = "http://localhost";
stub = sinon.stub(jwt, "decode").callsFake(() => { stub = sinon.stub(jwt, "decode").callsFake(() => {
return decodedToken; return decodedToken;
}); });
req.db.requestInviteToken.resolves(inviteToken); req.db.requestInviteToken.resolves(inviteToken);
req.settingsService.getSettings.returns({ clientHost }); req.settingsService.getSettings.returns({ clientHost });
await issueInvitation(req, res, next); await issueInvitation(req, res, next);
expect(res.status.calledWith(200)).to.be.true; expect(res.status.calledWith(200)).to.be.true;
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: "Invite sent", msg: "Invite sent",
data: inviteToken, data: inviteToken,
}) })
).to.be.true; ).to.be.true;
stub.restore(); stub.restore();
}); });
}); });
describe("inviteController - inviteVerifyController", () => { describe("inviteController - inviteVerifyController", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: { token: "token" }, body: { token: "token" },
db: { db: {
getInviteToken: sinon.stub(), getInviteToken: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if body validation fails", async () => { it("should reject with an error if body validation fails", async () => {
req.body = {}; req.body = {};
await inviteVerifyController(req, res, next); await inviteVerifyController(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if DB operations fail", async () => { it("should reject with an error if DB operations fail", async () => {
req.db.getInviteToken.throws(new Error("DB error")); req.db.getInviteToken.throws(new Error("DB error"));
await inviteVerifyController(req, res, next); await inviteVerifyController(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error"); expect(next.firstCall.args[0].message).to.equal("DB error");
}); });
it("should return 200 and invite data when validation and invite retrieval are successful", async () => { it("should return 200 and invite data when validation and invite retrieval are successful", async () => {
req.db.getInviteToken.resolves({ invite: "data" }); req.db.getInviteToken.resolves({ invite: "data" });
await inviteVerifyController(req, res, next); await inviteVerifyController(req, res, next);
expect(res.status.calledWith(200)).to.be.true; expect(res.status.calledWith(200)).to.be.true;
expect( expect(
res.json.calledWith({ res.json.calledWith({
status: "success", status: "success",
msg: "Invite verified", msg: "Invite verified",
data: { invite: "data" }, data: { invite: "data" },
}) })
).to.be.true; ).to.be.true;
expect(next.called).to.be.false; expect(next.called).to.be.false;
}); });
}); });
@@ -1,10 +1,10 @@
import { import {
createMaintenanceWindows, createMaintenanceWindows,
getMaintenanceWindowById, getMaintenanceWindowById,
getMaintenanceWindowsByTeamId, getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId, getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindow, deleteMaintenanceWindow,
editMaintenanceWindow, editMaintenanceWindow,
} from "../../controllers/maintenanceWindowController.js"; } from "../../controllers/maintenanceWindowController.js";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
@@ -12,405 +12,399 @@ import { successMessages } from "../../utils/messages.js";
import sinon from "sinon"; import sinon from "sinon";
describe("maintenanceWindowController - createMaintenanceWindows", () => { describe("maintenanceWindowController - createMaintenanceWindows", () => {
let req, res, next, stub; let req, res, next, stub;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: { body: {
monitors: ["66ff52e7c5911c61698ac724"], monitors: ["66ff52e7c5911c61698ac724"],
name: "window", name: "window",
active: true, active: true,
start: "2024-10-11T05:27:13.747Z", start: "2024-10-11T05:27:13.747Z",
end: "2024-10-11T05:27:14.747Z", end: "2024-10-11T05:27:14.747Z",
repeat: "123", repeat: "123",
}, },
headers: { headers: {
authorization: "Bearer token", authorization: "Bearer token",
}, },
settingsService: { settingsService: {
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }), getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
}, },
db: { db: {
createMaintenanceWindow: sinon.stub(), createMaintenanceWindow: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if body validation fails", async () => { it("should reject with an error if body validation fails", async () => {
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
}); });
req.body = {}; req.body = {};
await createMaintenanceWindows(req, res, next); await createMaintenanceWindows(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
stub.restore(); stub.restore();
}); });
it("should reject with an error if jwt.verify fails", async () => { it("should reject with an error if jwt.verify fails", async () => {
stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError()); stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError());
await createMaintenanceWindows(req, res, next); await createMaintenanceWindows(req, res, next);
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError); expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
stub.restore(); stub.restore();
}); });
it("should reject with an error DB operations fail", async () => { it("should reject with an error DB operations fail", async () => {
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
}); });
req.db.createMaintenanceWindow.throws(new Error("DB error")); req.db.createMaintenanceWindow.throws(new Error("DB error"));
await createMaintenanceWindows(req, res, next); await createMaintenanceWindows(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error"); expect(next.firstCall.args[0].message).to.equal("DB error");
stub.restore(); stub.restore();
}); });
it("should return success message if all operations are successful", async () => { it("should return success message if all operations are successful", async () => {
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
}); });
await createMaintenanceWindows(req, res, next); await createMaintenanceWindows(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(201); expect(res.status.firstCall.args[0]).to.equal(201);
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_CREATE, msg: successMessages.MAINTENANCE_WINDOW_CREATE,
}) })
).to.be.true; ).to.be.true;
stub.restore(); stub.restore();
}); });
it("should return success message if all operations are successful with active set to undefined", async () => { it("should return success message if all operations are successful with active set to undefined", async () => {
req.body.active = undefined; req.body.active = undefined;
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
}); });
await createMaintenanceWindows(req, res, next); await createMaintenanceWindows(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(201); expect(res.status.firstCall.args[0]).to.equal(201);
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_CREATE, msg: successMessages.MAINTENANCE_WINDOW_CREATE,
}) })
).to.be.true; ).to.be.true;
stub.restore(); stub.restore();
}); });
}); });
describe("maintenanceWindowController - getMaintenanceWindowById", () => { describe("maintenanceWindowController - getMaintenanceWindowById", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: {}, body: {},
params: { params: {
id: "123", id: "123",
}, },
headers: { headers: {
authorization: "Bearer token", authorization: "Bearer token",
}, },
settingsService: { settingsService: {
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }), getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
}, },
db: { db: {
getMaintenanceWindowById: sinon.stub(), getMaintenanceWindowById: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
it("should reject if param validation fails", async () => { it("should reject if param validation fails", async () => {
req.params = {}; req.params = {};
await getMaintenanceWindowById(req, res, next); await getMaintenanceWindowById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject if DB operations fail", async () => { it("should reject if DB operations fail", async () => {
req.db.getMaintenanceWindowById.throws(new Error("DB error")); req.db.getMaintenanceWindowById.throws(new Error("DB error"));
await getMaintenanceWindowById(req, res, next); await getMaintenanceWindowById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error"); expect(next.firstCall.args[0].message).to.equal("DB error");
}); });
it("should return success message with data if all operations are successful", async () => { it("should return success message with data if all operations are successful", async () => {
req.db.getMaintenanceWindowById.returns({ id: "123" }); req.db.getMaintenanceWindowById.returns({ id: "123" });
await getMaintenanceWindowById(req, res, next); await getMaintenanceWindowById(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200); expect(res.status.firstCall.args[0]).to.equal(200);
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID, msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID,
data: { id: "123" }, data: { id: "123" },
}) })
).to.be.true; ).to.be.true;
}); });
}); });
describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", () => { describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", () => {
let req, res, next, stub; let req, res, next, stub;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: {}, body: {},
params: {}, params: {},
query: {}, query: {},
headers: { headers: {
authorization: "Bearer token", authorization: "Bearer token",
}, },
settingsService: { settingsService: {
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }), getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
}, },
db: { db: {
getMaintenanceWindowsByTeamId: sinon.stub(), getMaintenanceWindowsByTeamId: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
it("should reject if query validation fails", async () => { it("should reject if query validation fails", async () => {
req.query = { req.query = {
invalid: 1, invalid: 1,
}; };
await getMaintenanceWindowsByTeamId(req, res, next); await getMaintenanceWindowsByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject if jwt.verify fails", async () => { it("should reject if jwt.verify fails", async () => {
stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError()); stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError());
await getMaintenanceWindowsByTeamId(req, res, next); await getMaintenanceWindowsByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError); expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
stub.restore(); stub.restore();
}); });
it("should reject with an error if DB operations fail", async () => { it("should reject with an error if DB operations fail", async () => {
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
}); });
req.db.getMaintenanceWindowsByTeamId.throws(new Error("DB error")); req.db.getMaintenanceWindowsByTeamId.throws(new Error("DB error"));
await getMaintenanceWindowsByTeamId(req, res, next); await getMaintenanceWindowsByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error"); expect(next.firstCall.args[0].message).to.equal("DB error");
stub.restore(); stub.restore();
}); });
it("should return success message with data if all operations are successful", async () => { it("should return success message with data if all operations are successful", async () => {
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
}); });
req.db.getMaintenanceWindowsByTeamId.returns([{ id: "123" }]); req.db.getMaintenanceWindowsByTeamId.returns([{ id: "123" }]);
await getMaintenanceWindowsByTeamId(req, res, next); await getMaintenanceWindowsByTeamId(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200); expect(res.status.firstCall.args[0]).to.equal(200);
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM, msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM,
data: [{ id: jwt.verify().teamId }], data: [{ id: jwt.verify().teamId }],
}) })
).to.be.true; ).to.be.true;
stub.restore(); stub.restore();
}); });
}); });
describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", () => { describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: {}, body: {},
params: { params: {
monitorId: "123", monitorId: "123",
}, },
query: {}, query: {},
headers: { headers: {
authorization: "Bearer token", authorization: "Bearer token",
}, },
settingsService: { settingsService: {
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }), getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
}, },
db: { db: {
getMaintenanceWindowsByMonitorId: sinon.stub(), getMaintenanceWindowsByMonitorId: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject if param validation fails", async () => { it("should reject if param validation fails", async () => {
req.params = {}; req.params = {};
await getMaintenanceWindowsByMonitorId(req, res, next); await getMaintenanceWindowsByMonitorId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if DB operations fail", async () => { it("should reject with an error if DB operations fail", async () => {
req.db.getMaintenanceWindowsByMonitorId.throws(new Error("DB error")); req.db.getMaintenanceWindowsByMonitorId.throws(new Error("DB error"));
await getMaintenanceWindowsByMonitorId(req, res, next); await getMaintenanceWindowsByMonitorId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error"); expect(next.firstCall.args[0].message).to.equal("DB error");
}); });
it("should return success message with data if all operations are successful", async () => { it("should return success message with data if all operations are successful", async () => {
const data = [{ monitorId: "123" }]; const data = [{ monitorId: "123" }];
req.db.getMaintenanceWindowsByMonitorId.returns(data); req.db.getMaintenanceWindowsByMonitorId.returns(data);
await getMaintenanceWindowsByMonitorId(req, res, next); await getMaintenanceWindowsByMonitorId(req, res, next);
expect( expect(req.db.getMaintenanceWindowsByMonitorId.calledOnceWith(req.params.monitorId));
req.db.getMaintenanceWindowsByMonitorId.calledOnceWith( expect(res.status.firstCall.args[0]).to.equal(200);
req.params.monitorId expect(
) res.json.calledOnceWith({
); success: true,
expect(res.status.firstCall.args[0]).to.equal(200); msg: successMessages.MAINTENANCE_WINDOW_GET_BY_MONITOR,
expect( data: data,
res.json.calledOnceWith({ })
success: true, ).to.be.true;
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_MONITOR, });
data: data,
})
).to.be.true;
});
}); });
describe("maintenanceWindowController - deleteMaintenanceWindow", () => { describe("maintenanceWindowController - deleteMaintenanceWindow", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: {}, body: {},
params: { params: {
id: "123", id: "123",
}, },
query: {}, query: {},
headers: { headers: {
authorization: "Bearer token", authorization: "Bearer token",
}, },
settingsService: { settingsService: {
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }), getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
}, },
db: { db: {
deleteMaintenanceWindowById: sinon.stub(), deleteMaintenanceWindowById: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject if param validation fails", async () => { it("should reject if param validation fails", async () => {
req.params = {}; req.params = {};
await deleteMaintenanceWindow(req, res, next); await deleteMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if DB operations fail", async () => { it("should reject with an error if DB operations fail", async () => {
req.db.deleteMaintenanceWindowById.throws(new Error("DB error")); req.db.deleteMaintenanceWindowById.throws(new Error("DB error"));
await deleteMaintenanceWindow(req, res, next); await deleteMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error"); expect(next.firstCall.args[0].message).to.equal("DB error");
}); });
it("should return success message if all operations are successful", async () => { it("should return success message if all operations are successful", async () => {
await deleteMaintenanceWindow(req, res, next); await deleteMaintenanceWindow(req, res, next);
expect(req.db.deleteMaintenanceWindowById.calledOnceWith(req.params.id)); expect(req.db.deleteMaintenanceWindowById.calledOnceWith(req.params.id));
expect(res.status.firstCall.args[0]).to.equal(200); expect(res.status.firstCall.args[0]).to.equal(200);
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_DELETE, msg: successMessages.MAINTENANCE_WINDOW_DELETE,
}) })
).to.be.true; ).to.be.true;
}); });
}); });
describe("maintenanceWindowController - editMaintenanceWindow", () => { describe("maintenanceWindowController - editMaintenanceWindow", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: { body: {
active: true, active: true,
name: "test", name: "test",
}, },
params: { params: {
id: "123", id: "123",
}, },
query: {}, query: {},
headers: { headers: {
authorization: "Bearer token", authorization: "Bearer token",
}, },
settingsService: { settingsService: {
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }), getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
}, },
db: { db: {
editMaintenanceWindowById: sinon.stub(), editMaintenanceWindowById: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject if param validation fails", async () => { it("should reject if param validation fails", async () => {
req.params = {}; req.params = {};
await editMaintenanceWindow(req, res, next); await editMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject if body validation fails", async () => { it("should reject if body validation fails", async () => {
req.body = { invalid: 1 }; req.body = { invalid: 1 };
await editMaintenanceWindow(req, res, next); await editMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if DB operations fail", async () => { it("should reject with an error if DB operations fail", async () => {
req.db.editMaintenanceWindowById.throws(new Error("DB error")); req.db.editMaintenanceWindowById.throws(new Error("DB error"));
await editMaintenanceWindow(req, res, next); await editMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error"); expect(next.firstCall.args[0].message).to.equal("DB error");
}); });
it("should return success message with data if all operations are successful", async () => { it("should return success message with data if all operations are successful", async () => {
const data = { id: "123" }; const data = { id: "123" };
req.db.editMaintenanceWindowById.returns(data); req.db.editMaintenanceWindowById.returns(data);
await editMaintenanceWindow(req, res, next); await editMaintenanceWindow(req, res, next);
expect( expect(req.db.editMaintenanceWindowById.calledOnceWith(req.params.id, req.body));
req.db.editMaintenanceWindowById.calledOnceWith(req.params.id, req.body) expect(res.status.firstCall.args[0]).to.equal(200);
); expect(
expect(res.status.firstCall.args[0]).to.equal(200); res.json.calledOnceWith({
expect( success: true,
res.json.calledOnceWith({ msg: successMessages.MAINTENANCE_WINDOW_EDIT,
success: true, data: data,
msg: successMessages.MAINTENANCE_WINDOW_EDIT, })
data: data, ).to.be.true;
}) });
).to.be.true;
});
}); });
+148 -148
View File
@@ -1,166 +1,166 @@
import { afterEach } from "node:test"; import { afterEach } from "node:test";
import { import {
getMetrics, getMetrics,
getJobs, getJobs,
addJob, addJob,
obliterateQueue, obliterateQueue,
} from "../../controllers/queueController.js"; } from "../../controllers/queueController.js";
import { successMessages } from "../../utils/messages.js"; import { successMessages } from "../../utils/messages.js";
import sinon from "sinon"; import sinon from "sinon";
describe("Queue Controller - getMetrics", () => { describe("Queue Controller - getMetrics", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: {}, headers: {},
params: {}, params: {},
body: {}, body: {},
db: {}, db: {},
jobQueue: { jobQueue: {
getMetrics: sinon.stub(), getMetrics: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should throw an error if getMetrics throws an error", async () => { it("should throw an error if getMetrics throws an error", async () => {
req.jobQueue.getMetrics.throws(new Error("getMetrics error")); req.jobQueue.getMetrics.throws(new Error("getMetrics error"));
await getMetrics(req, res, next); await getMetrics(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getMetrics error"); expect(next.firstCall.args[0].message).to.equal("getMetrics error");
}); });
it("should return a success message and data if getMetrics is successful", async () => { it("should return a success message and data if getMetrics is successful", async () => {
const data = { data: "metrics" }; const data = { data: "metrics" };
req.jobQueue.getMetrics.returns(data); req.jobQueue.getMetrics.returns(data);
await getMetrics(req, res, next); await getMetrics(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200); expect(res.status.firstCall.args[0]).to.equal(200);
expect(res.json.firstCall.args[0]).to.deep.equal({ expect(res.json.firstCall.args[0]).to.deep.equal({
success: true, success: true,
msg: successMessages.QUEUE_GET_METRICS, msg: successMessages.QUEUE_GET_METRICS,
data, data,
}); });
}); });
}); });
describe("Queue Controller - getJobs", () => { describe("Queue Controller - getJobs", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: {}, headers: {},
params: {}, params: {},
body: {}, body: {},
db: {}, db: {},
jobQueue: { jobQueue: {
getJobStats: sinon.stub(), getJobStats: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if getJobs throws an error", async () => { it("should reject with an error if getJobs throws an error", async () => {
req.jobQueue.getJobStats.throws(new Error("getJobs error")); req.jobQueue.getJobStats.throws(new Error("getJobs error"));
await getJobs(req, res, next); await getJobs(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getJobs error"); expect(next.firstCall.args[0].message).to.equal("getJobs error");
}); });
it("should return a success message and data if getJobs is successful", async () => { it("should return a success message and data if getJobs is successful", async () => {
const data = { data: "jobs" }; const data = { data: "jobs" };
req.jobQueue.getJobStats.returns(data); req.jobQueue.getJobStats.returns(data);
await getJobs(req, res, next); await getJobs(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200); expect(res.status.firstCall.args[0]).to.equal(200);
expect(res.json.firstCall.args[0]).to.deep.equal({ expect(res.json.firstCall.args[0]).to.deep.equal({
success: true, success: true,
msg: successMessages.QUEUE_GET_METRICS, msg: successMessages.QUEUE_GET_METRICS,
data, data,
}); });
}); });
}); });
describe("Queue Controller - addJob", () => { describe("Queue Controller - addJob", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: {}, headers: {},
params: {}, params: {},
body: {}, body: {},
db: {}, db: {},
jobQueue: { jobQueue: {
addJob: sinon.stub(), addJob: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if addJob throws an error", async () => { it("should reject with an error if addJob throws an error", async () => {
req.jobQueue.addJob.throws(new Error("addJob error")); req.jobQueue.addJob.throws(new Error("addJob error"));
await addJob(req, res, next); await addJob(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("addJob error"); expect(next.firstCall.args[0].message).to.equal("addJob error");
}); });
it("should return a success message if addJob is successful", async () => { it("should return a success message if addJob is successful", async () => {
req.jobQueue.addJob.resolves(); req.jobQueue.addJob.resolves();
await addJob(req, res, next); await addJob(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200); expect(res.status.firstCall.args[0]).to.equal(200);
expect(res.json.firstCall.args[0]).to.deep.equal({ expect(res.json.firstCall.args[0]).to.deep.equal({
success: true, success: true,
msg: successMessages.QUEUE_ADD_JOB, msg: successMessages.QUEUE_ADD_JOB,
}); });
}); });
}); });
describe("Queue Controller - obliterateQueue", () => { describe("Queue Controller - obliterateQueue", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: {}, headers: {},
params: {}, params: {},
body: {}, body: {},
db: {}, db: {},
jobQueue: { jobQueue: {
obliterate: sinon.stub(), obliterate: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if obliterateQueue throws an error", async () => { it("should reject with an error if obliterateQueue throws an error", async () => {
req.jobQueue.obliterate.throws(new Error("obliterateQueue error")); req.jobQueue.obliterate.throws(new Error("obliterateQueue error"));
await obliterateQueue(req, res, next); await obliterateQueue(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("obliterateQueue error"); expect(next.firstCall.args[0].message).to.equal("obliterateQueue error");
}); });
it("should return a success message if obliterateQueue is successful", async () => { it("should return a success message if obliterateQueue is successful", async () => {
req.jobQueue.obliterate.resolves(); req.jobQueue.obliterate.resolves();
await obliterateQueue(req, res, next); await obliterateQueue(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200); expect(res.status.firstCall.args[0]).to.equal(200);
expect(res.json.firstCall.args[0]).to.deep.equal({ expect(res.json.firstCall.args[0]).to.deep.equal({
success: true, success: true,
msg: successMessages.QUEUE_OBLITERATE, msg: successMessages.QUEUE_OBLITERATE,
}); });
}); });
}); });
@@ -1,105 +1,103 @@
import { afterEach } from "node:test"; import { afterEach } from "node:test";
import { import {
getAppSettings, getAppSettings,
updateAppSettings, updateAppSettings,
} from "../../controllers/settingsController.js"; } from "../../controllers/settingsController.js";
import { successMessages } from "../../utils/messages.js"; import { successMessages } from "../../utils/messages.js";
import sinon from "sinon"; import sinon from "sinon";
describe("Settings Controller - getAppSettings", () => { describe("Settings Controller - getAppSettings", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: {}, headers: {},
params: {}, params: {},
body: {}, body: {},
db: {}, db: {},
settingsService: { settingsService: {
getSettings: sinon.stub(), getSettings: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should throw an error if getSettings throws an error", async () => { it("should throw an error if getSettings throws an error", async () => {
req.settingsService.getSettings.throws(new Error("getSettings error")); req.settingsService.getSettings.throws(new Error("getSettings error"));
await getAppSettings(req, res, next); await getAppSettings(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getSettings error"); expect(next.firstCall.args[0].message).to.equal("getSettings error");
}); });
it("should return a success message and data if getSettings is successful", async () => { it("should return a success message and data if getSettings is successful", async () => {
const data = { data: "settings" }; const data = { data: "settings" };
req.settingsService.getSettings.returns(data); req.settingsService.getSettings.returns(data);
await getAppSettings(req, res, next); await getAppSettings(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200); expect(res.status.firstCall.args[0]).to.equal(200);
expect(res.json.firstCall.args[0]).to.deep.equal({ expect(res.json.firstCall.args[0]).to.deep.equal({
success: true, success: true,
msg: successMessages.GET_APP_SETTINGS, msg: successMessages.GET_APP_SETTINGS,
data, data,
}); });
}); });
}); });
describe("Settings Controller - updateAppSettings", () => { describe("Settings Controller - updateAppSettings", () => {
let req, res, next; let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: {}, headers: {},
params: {}, params: {},
body: {}, body: {},
db: { db: {
updateAppSettings: sinon.stub(), updateAppSettings: sinon.stub(),
}, },
settingsService: { settingsService: {
reloadSettings: sinon.stub(), reloadSettings: sinon.stub(),
}, },
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if body validation fails", async () => { it("should reject with an error if body validation fails", async () => {
req.body = { invalid: 1 }; req.body = { invalid: 1 };
await updateAppSettings(req, res, next); await updateAppSettings(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if updateAppSettings throws an error", async () => { it("should reject with an error if updateAppSettings throws an error", async () => {
req.db.updateAppSettings.throws(new Error("updateAppSettings error")); req.db.updateAppSettings.throws(new Error("updateAppSettings error"));
await updateAppSettings(req, res, next); await updateAppSettings(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("updateAppSettings error"); expect(next.firstCall.args[0].message).to.equal("updateAppSettings error");
}); });
it("should reject with an error if reloadSettings throws an error", async () => { it("should reject with an error if reloadSettings throws an error", async () => {
req.settingsService.reloadSettings.throws( req.settingsService.reloadSettings.throws(new Error("reloadSettings error"));
new Error("reloadSettings error") await updateAppSettings(req, res, next);
); expect(next.firstCall.args[0]).to.be.an("error");
await updateAppSettings(req, res, next); expect(next.firstCall.args[0].message).to.equal("reloadSettings error");
expect(next.firstCall.args[0]).to.be.an("error"); });
expect(next.firstCall.args[0].message).to.equal("reloadSettings error"); it("should return a success message and data if updateAppSettings is successful", async () => {
}); const data = { data: "settings" };
it("should return a success message and data if updateAppSettings is successful", async () => { req.settingsService.reloadSettings.returns(data);
const data = { data: "settings" }; await updateAppSettings(req, res, next);
req.settingsService.reloadSettings.returns(data); expect(res.status.firstCall.args[0]).to.equal(200);
await updateAppSettings(req, res, next); expect(res.json.firstCall.args[0]).to.deep.equal({
expect(res.status.firstCall.args[0]).to.equal(200); success: true,
expect(res.json.firstCall.args[0]).to.deep.equal({ msg: successMessages.UPDATE_APP_SETTINGS,
success: true, data,
msg: successMessages.UPDATE_APP_SETTINGS, });
data, });
});
});
}); });
File diff suppressed because it is too large. Load diff
+15 -15
View File
@@ -4,22 +4,22 @@ import sharp from "sharp";
* @param {} file * @param {} file
*/ */
const GenerateAvatarImage = async (file) => { const GenerateAvatarImage = async (file) => {
try { try {
// Resize to target 64 * 64 // Resize to target 64 * 64
let resizedImageBuffer = await sharp(file.buffer) let resizedImageBuffer = await sharp(file.buffer)
.resize({ .resize({
width: 64, width: 64,
height: 64, height: 64,
fit: "cover", fit: "cover",
}) })
.toBuffer(); .toBuffer();
//Get b64 string //Get b64 string
const base64Image = resizedImageBuffer.toString("base64"); const base64Image = resizedImageBuffer.toString("base64");
return base64Image; return base64Image;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };
export { GenerateAvatarImage }; export { GenerateAvatarImage };
+6 -9
View File
@@ -12,15 +12,12 @@ import winston from "winston";
* logger.error("User not found!",{"service":"Auth"}) * logger.error("User not found!",{"service":"Auth"})
*/ */
const logger = winston.createLogger({ const logger = winston.createLogger({
level: "info", level: "info",
format: winston.format.combine( format: winston.format.combine(winston.format.timestamp(), winston.format.json()),
winston.format.timestamp(), transports: [
winston.format.json() new winston.transports.Console(),
), new winston.transports.File({ filename: "app.log" }),
transports: [ ],
new winston.transports.Console(),
new winston.transports.File({ filename: "app.log" }),
],
}); });
export default logger; export default logger;
+95 -99
View File
@@ -1,124 +1,120 @@
const errorMessages = { const errorMessages = {
// General Errors: // General Errors:
FRIENDLY_ERROR: "Something went wrong...", FRIENDLY_ERROR: "Something went wrong...",
UNKNOWN_ERROR: "An unknown error occurred", UNKNOWN_ERROR: "An unknown error occurred",
// Auth Controller // Auth Controller
UNAUTHORIZED: "Unauthorized access", UNAUTHORIZED: "Unauthorized access",
AUTH_ADMIN_EXISTS: "Admin already exists", AUTH_ADMIN_EXISTS: "Admin already exists",
AUTH_INVITE_NOT_FOUND: "Invite not found", AUTH_INVITE_NOT_FOUND: "Invite not found",
//Error handling middleware //Error handling middleware
UNKNOWN_SERVICE: "Unknown service", UNKNOWN_SERVICE: "Unknown service",
NO_AUTH_TOKEN: "No auth token provided", NO_AUTH_TOKEN: "No auth token provided",
INVALID_AUTH_TOKEN: "Invalid auth token", INVALID_AUTH_TOKEN: "Invalid auth token",
EXPIRED_AUTH_TOKEN: "Token expired", EXPIRED_AUTH_TOKEN: "Token expired",
NO_REFRESH_TOKEN: "No refresh token provided", NO_REFRESH_TOKEN: "No refresh token provided",
INVALID_REFRESH_TOKEN: "Invalid refresh token", INVALID_REFRESH_TOKEN: "Invalid refresh token",
EXPIRED_REFRESH_TOKEN: "Refresh token expired", EXPIRED_REFRESH_TOKEN: "Refresh token expired",
REQUEST_NEW_ACCESS_TOKEN: "Request new access token", REQUEST_NEW_ACCESS_TOKEN: "Request new access token",
//Payload //Payload
INVALID_PAYLOAD: "Invalid payload", INVALID_PAYLOAD: "Invalid payload",
//Ownership Middleware //Ownership Middleware
VERIFY_OWNER_NOT_FOUND: "Document not found", VERIFY_OWNER_NOT_FOUND: "Document not found",
VERIFY_OWNER_UNAUTHORIZED: "Unauthorized access", VERIFY_OWNER_UNAUTHORIZED: "Unauthorized access",
//Permissions Middleware //Permissions Middleware
INSUFFICIENT_PERMISSIONS: "Insufficient permissions", INSUFFICIENT_PERMISSIONS: "Insufficient permissions",
//DB Errors //DB Errors
DB_USER_EXISTS: "User already exists", DB_USER_EXISTS: "User already exists",
DB_USER_NOT_FOUND: "User not found", DB_USER_NOT_FOUND: "User not found",
DB_TOKEN_NOT_FOUND: "Token not found", DB_TOKEN_NOT_FOUND: "Token not found",
DB_RESET_PASSWORD_BAD_MATCH: DB_RESET_PASSWORD_BAD_MATCH: "New password must be different from old password",
"New password must be different from old password", DB_FIND_MONITOR_BY_ID: (monitorId) => `Monitor with id ${monitorId} not found`,
DB_FIND_MONITOR_BY_ID: (monitorId) => DB_DELETE_CHECKS: (monitorId) => `No checks found for monitor with id ${monitorId}`,
`Monitor with id ${monitorId} not found`,
DB_DELETE_CHECKS: (monitorId) =>
`No checks found for monitor with id ${monitorId}`,
//Auth errors //Auth errors
AUTH_INCORRECT_PASSWORD: "Incorrect password", AUTH_INCORRECT_PASSWORD: "Incorrect password",
AUTH_UNAUTHORIZED: "Unauthorized access", AUTH_UNAUTHORIZED: "Unauthorized access",
// Monitor Errors // Monitor Errors
MONITOR_GET_BY_ID: "Monitor not found", MONITOR_GET_BY_ID: "Monitor not found",
MONITOR_GET_BY_USER_ID: "No monitors found for user", MONITOR_GET_BY_USER_ID: "No monitors found for user",
// Job Queue Errors // Job Queue Errors
JOB_QUEUE_WORKER_CLOSE: "Error closing worker", JOB_QUEUE_WORKER_CLOSE: "Error closing worker",
JOB_QUEUE_DELETE_JOB: "Job not found in queue", JOB_QUEUE_DELETE_JOB: "Job not found in queue",
JOB_QUEUE_OBLITERATE: "Error obliterating queue", JOB_QUEUE_OBLITERATE: "Error obliterating queue",
// PING Operations // PING Operations
PING_CANNOT_RESOLVE: "No response", PING_CANNOT_RESOLVE: "No response",
}; };
const successMessages = { const successMessages = {
//Alert Controller //Alert Controller
ALERT_CREATE: "Alert created successfully", ALERT_CREATE: "Alert created successfully",
ALERT_GET_BY_USER: "Got alerts successfully", ALERT_GET_BY_USER: "Got alerts successfully",
ALERT_GET_BY_MONITOR: "Got alerts by Monitor successfully", ALERT_GET_BY_MONITOR: "Got alerts by Monitor successfully",
ALERT_GET_BY_ID: "Got alert by Id successfully", ALERT_GET_BY_ID: "Got alert by Id successfully",
ALERT_EDIT: "Alert edited successfully", ALERT_EDIT: "Alert edited successfully",
ALERT_DELETE: "Alert deleted successfully", ALERT_DELETE: "Alert deleted successfully",
// Auth Controller // Auth Controller
AUTH_CREATE_USER: "User created successfully", AUTH_CREATE_USER: "User created successfully",
AUTH_LOGIN_USER: "User logged in successfully", AUTH_LOGIN_USER: "User logged in successfully",
AUTH_LOGOUT_USER: "User logged out successfully", AUTH_LOGOUT_USER: "User logged out successfully",
AUTH_UPDATE_USER: "User updated successfully", AUTH_UPDATE_USER: "User updated successfully",
AUTH_CREATE_RECOVERY_TOKEN: "Recovery token created successfully", AUTH_CREATE_RECOVERY_TOKEN: "Recovery token created successfully",
AUTH_VERIFY_RECOVERY_TOKEN: "Recovery token verified successfully", AUTH_VERIFY_RECOVERY_TOKEN: "Recovery token verified successfully",
AUTH_RESET_PASSWORD: "Password reset successfully", AUTH_RESET_PASSWORD: "Password reset successfully",
AUTH_ADMIN_CHECK: "Admin check completed successfully", AUTH_ADMIN_CHECK: "Admin check completed successfully",
AUTH_DELETE_USER: "User deleted successfully", AUTH_DELETE_USER: "User deleted successfully",
// Check Controller // Check Controller
CHECK_CREATE: "Check created successfully", CHECK_CREATE: "Check created successfully",
CHECK_GET: "Got checks successfully", CHECK_GET: "Got checks successfully",
CHECK_DELETE: "Checks deleted successfully", CHECK_DELETE: "Checks deleted successfully",
CHECK_UPDATE_TTL: "Checks TTL updated successfully", CHECK_UPDATE_TTL: "Checks TTL updated successfully",
//Monitor Controller //Monitor Controller
MONITOR_GET_ALL: "Got all monitors successfully", MONITOR_GET_ALL: "Got all monitors successfully",
MONITOR_STATS_BY_ID: "Got monitor stats by Id successfully", MONITOR_STATS_BY_ID: "Got monitor stats by Id successfully",
MONITOR_GET_BY_ID: "Got monitor by Id successfully", MONITOR_GET_BY_ID: "Got monitor by Id successfully",
MONITOR_GET_BY_USER_ID: (userId) => `Got monitor for ${userId} successfully"`, MONITOR_GET_BY_USER_ID: (userId) => `Got monitor for ${userId} successfully"`,
MONITOR_CREATE: "Monitor created successfully", MONITOR_CREATE: "Monitor created successfully",
MONITOR_DELETE: "Monitor deleted successfully", MONITOR_DELETE: "Monitor deleted successfully",
MONITOR_EDIT: "Monitor edited successfully", MONITOR_EDIT: "Monitor edited successfully",
MONITOR_CERTIFICATE: "Got monitor certificate successfully", MONITOR_CERTIFICATE: "Got monitor certificate successfully",
MONITOR_DEMO_ADDED: "Successfully added demo monitors", MONITOR_DEMO_ADDED: "Successfully added demo monitors",
// Queue Controller // Queue Controller
QUEUE_GET_METRICS: "Got metrics successfully", QUEUE_GET_METRICS: "Got metrics successfully",
QUEUE_GET_METRICS: "Got job stats successfully", QUEUE_GET_METRICS: "Got job stats successfully",
QUEUE_ADD_JOB: "Job added successfully", QUEUE_ADD_JOB: "Job added successfully",
QUEUE_OBLITERATE: "Queue obliterated", QUEUE_OBLITERATE: "Queue obliterated",
//Job Queue //Job Queue
JOB_QUEUE_DELETE_JOB: "Job removed successfully", JOB_QUEUE_DELETE_JOB: "Job removed successfully",
JOB_QUEUE_OBLITERATE: "Queue OBLITERATED!!!", JOB_QUEUE_OBLITERATE: "Queue OBLITERATED!!!",
JOB_QUEUE_PAUSE_JOB: "Job paused successfully", JOB_QUEUE_PAUSE_JOB: "Job paused successfully",
JOB_QUEUE_RESUME_JOB: "Job resumed successfully", JOB_QUEUE_RESUME_JOB: "Job resumed successfully",
//Maintenance Window Controller //Maintenance Window Controller
MAINTENANCE_WINDOW_GET_BY_ID: "Got Maintenance Window by Id successfully", MAINTENANCE_WINDOW_GET_BY_ID: "Got Maintenance Window by Id successfully",
MAINTENANCE_WINDOW_CREATE: "Maintenance Window created successfully", MAINTENANCE_WINDOW_CREATE: "Maintenance Window created successfully",
MAINTENANCE_WINDOW_GET_BY_TEAM: MAINTENANCE_WINDOW_GET_BY_TEAM: "Got Maintenance Windows by Team successfully",
"Got Maintenance Windows by Team successfully", MAINTENANCE_WINDOW_DELETE: "Maintenance Window deleted successfully",
MAINTENANCE_WINDOW_DELETE: "Maintenance Window deleted successfully", MAINTENANCE_WINDOW_EDIT: "Maintenance Window edited successfully",
MAINTENANCE_WINDOW_EDIT: "Maintenance Window edited successfully",
//Ping Operations //Ping Operations
PING_SUCCESS: "Success", PING_SUCCESS: "Success",
// App Settings // App Settings
GET_APP_SETTINGS: "Got app settings successfully", GET_APP_SETTINGS: "Got app settings successfully",
UPDATE_APP_SETTINGS: "Updated app settings successfully", UPDATE_APP_SETTINGS: "Updated app settings successfully",
}; };
export { errorMessages, successMessages }; export { errorMessages, successMessages };
+286 -286
View File
@@ -5,13 +5,13 @@ import joi from "joi";
//**************************************** //****************************************
const roleValidatior = (role) => (value, helpers) => { const roleValidatior = (role) => (value, helpers) => {
const hasRole = role.some((role) => value.includes(role)); const hasRole = role.some((role) => value.includes(role));
if (!hasRole) { if (!hasRole) {
throw new joi.ValidationError( throw new joi.ValidationError(
`You do not have the required authorization. Required roles: ${role.join(", ")}` `You do not have the required authorization. Required roles: ${role.join(", ")}`
); );
} }
return value; return value;
}; };
//**************************************** //****************************************
@@ -19,129 +19,129 @@ const roleValidatior = (role) => (value, helpers) => {
//**************************************** //****************************************
const loginValidation = joi.object({ const loginValidation = joi.object({
email: joi email: joi
.string() .string()
.email() .email()
.required() .required()
.custom((value, helpers) => { .custom((value, helpers) => {
const lowercasedValue = value.toLowerCase(); const lowercasedValue = value.toLowerCase();
if (value !== lowercasedValue) { if (value !== lowercasedValue) {
return helpers.message("Email must be in lowercase"); return helpers.message("Email must be in lowercase");
} }
return lowercasedValue; return lowercasedValue;
}), }),
password: joi password: joi
.string() .string()
.min(8) .min(8)
.required() .required()
.pattern( .pattern(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/ /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/
), ),
}); });
const registrationBodyValidation = joi.object({ const registrationBodyValidation = joi.object({
firstName: joi firstName: joi
.string() .string()
.required() .required()
.pattern(/^[A-Za-z]+$/), .pattern(/^[A-Za-z]+$/),
lastName: joi lastName: joi
.string() .string()
.required() .required()
.pattern(/^[A-Za-z]+$/), .pattern(/^[A-Za-z]+$/),
email: joi email: joi
.string() .string()
.email() .email()
.required() .required()
.custom((value, helpers) => { .custom((value, helpers) => {
const lowercasedValue = value.toLowerCase(); const lowercasedValue = value.toLowerCase();
if (value !== lowercasedValue) { if (value !== lowercasedValue) {
return helpers.message("Email must be in lowercase"); return helpers.message("Email must be in lowercase");
} }
return lowercasedValue; return lowercasedValue;
}), }),
password: joi password: joi
.string() .string()
.min(8) .min(8)
.required() .required()
.pattern( .pattern(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/ /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/
), ),
profileImage: joi.any(), profileImage: joi.any(),
role: joi role: joi
.array() .array()
.items(joi.string().valid("superadmin", "admin", "user", "demo")) .items(joi.string().valid("superadmin", "admin", "user", "demo"))
.min(1) .min(1)
.required(), .required(),
teamId: joi.string().allow("").required(), teamId: joi.string().allow("").required(),
inviteToken: joi.string().allow("").required(), inviteToken: joi.string().allow("").required(),
}); });
const editUserParamValidation = joi.object({ const editUserParamValidation = joi.object({
userId: joi.string().required(), userId: joi.string().required(),
}); });
const editUserBodyValidation = joi.object({ const editUserBodyValidation = joi.object({
firstName: joi.string().pattern(/^[A-Za-z]+$/), firstName: joi.string().pattern(/^[A-Za-z]+$/),
lastName: joi.string().pattern(/^[A-Za-z]+$/), lastName: joi.string().pattern(/^[A-Za-z]+$/),
profileImage: joi.any(), profileImage: joi.any(),
newPassword: joi newPassword: joi
.string() .string()
.min(8) .min(8)
.pattern( .pattern(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/ /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/
), ),
password: joi password: joi
.string() .string()
.min(8) .min(8)
.pattern( .pattern(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/ /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/
), ),
deleteProfileImage: joi.boolean(), deleteProfileImage: joi.boolean(),
role: joi.array(), role: joi.array(),
}); });
const recoveryValidation = joi.object({ const recoveryValidation = joi.object({
email: joi email: joi
.string() .string()
.email({ tlds: { allow: false } }) .email({ tlds: { allow: false } })
.required(), .required(),
}); });
const recoveryTokenValidation = joi.object({ const recoveryTokenValidation = joi.object({
recoveryToken: joi.string().required(), recoveryToken: joi.string().required(),
}); });
const newPasswordValidation = joi.object({ const newPasswordValidation = joi.object({
recoveryToken: joi.string().required(), recoveryToken: joi.string().required(),
password: joi password: joi
.string() .string()
.min(8) .min(8)
.required() .required()
.pattern( .pattern(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/ /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[A-Za-z0-9!@#$%^&*()]+$/
), ),
confirm: joi.string(), confirm: joi.string(),
}); });
const deleteUserParamValidation = joi.object({ const deleteUserParamValidation = joi.object({
email: joi.string().email().required(), email: joi.string().email().required(),
}); });
const inviteRoleValidation = joi.object({ const inviteRoleValidation = joi.object({
roles: joi.custom(roleValidatior(["admin", "superadmin"])).required(), roles: joi.custom(roleValidatior(["admin", "superadmin"])).required(),
}); });
const inviteBodyValidation = joi.object({ const inviteBodyValidation = joi.object({
email: joi.string().trim().email().required().messages({ email: joi.string().trim().email().required().messages({
"string.empty": "Email is required", "string.empty": "Email is required",
"string.email": "Must be a valid email address", "string.email": "Must be a valid email address",
}), }),
role: joi.array().required(), role: joi.array().required(),
teamId: joi.string().required(), teamId: joi.string().required(),
}); });
const inviteVerificationBodyValidation = joi.object({ const inviteVerificationBodyValidation = joi.object({
token: joi.string().required(), token: joi.string().required(),
}); });
//**************************************** //****************************************
@@ -149,91 +149,91 @@ const inviteVerificationBodyValidation = joi.object({
//**************************************** //****************************************
const getMonitorByIdParamValidation = joi.object({ const getMonitorByIdParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
const getMonitorByIdQueryValidation = joi.object({ const getMonitorByIdQueryValidation = joi.object({
status: joi.boolean(), status: joi.boolean(),
sortOrder: joi.string().valid("asc", "desc"), sortOrder: joi.string().valid("asc", "desc"),
limit: joi.number(), limit: joi.number(),
dateRange: joi.string().valid("day", "week", "month"), dateRange: joi.string().valid("day", "week", "month"),
numToDisplay: joi.number(), numToDisplay: joi.number(),
normalize: joi.boolean(), normalize: joi.boolean(),
}); });
const getMonitorsAndSummaryByTeamIdParamValidation = joi.object({ const getMonitorsAndSummaryByTeamIdParamValidation = joi.object({
teamId: joi.string().required(), teamId: joi.string().required(),
}); });
const getMonitorsAndSummaryByTeamIdQueryValidation = joi.object({ const getMonitorsAndSummaryByTeamIdQueryValidation = joi.object({
type: joi type: joi
.alternatives() .alternatives()
.try( .try(
joi.string().valid("http", "ping", "pagespeed"), joi.string().valid("http", "ping", "pagespeed"),
joi.array().items(joi.string().valid("http", "ping", "pagespeed")) joi.array().items(joi.string().valid("http", "ping", "pagespeed"))
), ),
}); });
const getMonitorsByTeamIdValidation = joi.object({ const getMonitorsByTeamIdValidation = joi.object({
teamId: joi.string().required(), teamId: joi.string().required(),
}); });
const getMonitorsByTeamIdQueryValidation = joi.object({ const getMonitorsByTeamIdQueryValidation = joi.object({
status: joi.boolean(), status: joi.boolean(),
checkOrder: joi.string().valid("asc", "desc"), checkOrder: joi.string().valid("asc", "desc"),
limit: joi.number(), limit: joi.number(),
normalize: joi.boolean(), normalize: joi.boolean(),
type: joi type: joi
.alternatives() .alternatives()
.try( .try(
joi.string().valid("http", "ping", "pagespeed"), joi.string().valid("http", "ping", "pagespeed"),
joi.array().items(joi.string().valid("http", "ping", "pagespeed")) joi.array().items(joi.string().valid("http", "ping", "pagespeed"))
), ),
page: joi.number(), page: joi.number(),
rowsPerPage: joi.number(), rowsPerPage: joi.number(),
filter: joi.string(), filter: joi.string(),
field: joi.string(), field: joi.string(),
order: joi.string().valid("asc", "desc"), order: joi.string().valid("asc", "desc"),
}); });
const getMonitorStatsByIdParamValidation = joi.object({ const getMonitorStatsByIdParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
const getMonitorStatsByIdQueryValidation = joi.object({ const getMonitorStatsByIdQueryValidation = joi.object({
status: joi.string(), status: joi.string(),
limit: joi.number(), limit: joi.number(),
sortOrder: joi.string().valid("asc", "desc"), sortOrder: joi.string().valid("asc", "desc"),
dateRange: joi.string().valid("day", "week", "month"), dateRange: joi.string().valid("day", "week", "month"),
numToDisplay: joi.number(), numToDisplay: joi.number(),
normalize: joi.boolean(), normalize: joi.boolean(),
}); });
const getCertificateParamValidation = joi.object({ const getCertificateParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
const createMonitorBodyValidation = joi.object({ const createMonitorBodyValidation = joi.object({
_id: joi.string(), _id: joi.string(),
userId: joi.string().required(), userId: joi.string().required(),
teamId: joi.string().required(), teamId: joi.string().required(),
name: joi.string().required(), name: joi.string().required(),
description: joi.string().required(), description: joi.string().required(),
type: joi.string().required(), type: joi.string().required(),
url: joi.string().required(), url: joi.string().required(),
isActive: joi.boolean(), isActive: joi.boolean(),
interval: joi.number(), interval: joi.number(),
notifications: joi.array().items(joi.object()), notifications: joi.array().items(joi.object()),
}); });
const editMonitorBodyValidation = joi.object({ const editMonitorBodyValidation = joi.object({
name: joi.string(), name: joi.string(),
description: joi.string(), description: joi.string(),
interval: joi.number(), interval: joi.number(),
notifications: joi.array().items(joi.object()), notifications: joi.array().items(joi.object()),
}); });
const pauseMonitorParamValidation = joi.object({ const pauseMonitorParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
//**************************************** //****************************************
@@ -241,44 +241,44 @@ const pauseMonitorParamValidation = joi.object({
//**************************************** //****************************************
const createAlertParamValidation = joi.object({ const createAlertParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
const createAlertBodyValidation = joi.object({ const createAlertBodyValidation = joi.object({
checkId: joi.string().required(), checkId: joi.string().required(),
monitorId: joi.string().required(), monitorId: joi.string().required(),
userId: joi.string().required(), userId: joi.string().required(),
status: joi.boolean(), status: joi.boolean(),
message: joi.string(), message: joi.string(),
notifiedStatus: joi.boolean(), notifiedStatus: joi.boolean(),
acknowledgeStatus: joi.boolean(), acknowledgeStatus: joi.boolean(),
}); });
const getAlertsByUserIdParamValidation = joi.object({ const getAlertsByUserIdParamValidation = joi.object({
userId: joi.string().required(), userId: joi.string().required(),
}); });
const getAlertsByMonitorIdParamValidation = joi.object({ const getAlertsByMonitorIdParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
const getAlertByIdParamValidation = joi.object({ const getAlertByIdParamValidation = joi.object({
alertId: joi.string().required(), alertId: joi.string().required(),
}); });
const editAlertParamValidation = joi.object({ const editAlertParamValidation = joi.object({
alertId: joi.string().required(), alertId: joi.string().required(),
}); });
const editAlertBodyValidation = joi.object({ const editAlertBodyValidation = joi.object({
status: joi.boolean(), status: joi.boolean(),
message: joi.string(), message: joi.string(),
notifiedStatus: joi.boolean(), notifiedStatus: joi.boolean(),
acknowledgeStatus: joi.boolean(), acknowledgeStatus: joi.boolean(),
}); });
const deleteAlertParamValidation = joi.object({ const deleteAlertParamValidation = joi.object({
alertId: joi.string().required(), alertId: joi.string().required(),
}); });
//**************************************** //****************************************
@@ -286,53 +286,53 @@ const deleteAlertParamValidation = joi.object({
//**************************************** //****************************************
const createCheckParamValidation = joi.object({ const createCheckParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
const createCheckBodyValidation = joi.object({ const createCheckBodyValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
status: joi.boolean().required(), status: joi.boolean().required(),
responseTime: joi.number().required(), responseTime: joi.number().required(),
statusCode: joi.number().required(), statusCode: joi.number().required(),
message: joi.string().required(), message: joi.string().required(),
}); });
const getChecksParamValidation = joi.object({ const getChecksParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
const getChecksQueryValidation = joi.object({ const getChecksQueryValidation = joi.object({
sortOrder: joi.string().valid("asc", "desc"), sortOrder: joi.string().valid("asc", "desc"),
limit: joi.number(), limit: joi.number(),
dateRange: joi.string().valid("day", "week", "month"), dateRange: joi.string().valid("day", "week", "month"),
filter: joi.string().valid("all", "down", "resolve"), filter: joi.string().valid("all", "down", "resolve"),
page: joi.number(), page: joi.number(),
rowsPerPage: joi.number(), rowsPerPage: joi.number(),
}); });
const getTeamChecksParamValidation = joi.object({ const getTeamChecksParamValidation = joi.object({
teamId: joi.string().required(), teamId: joi.string().required(),
}); });
const getTeamChecksQueryValidation = joi.object({ const getTeamChecksQueryValidation = joi.object({
sortOrder: joi.string().valid("asc", "desc"), sortOrder: joi.string().valid("asc", "desc"),
limit: joi.number(), limit: joi.number(),
dateRange: joi.string().valid("day", "week", "month"), dateRange: joi.string().valid("day", "week", "month"),
filter: joi.string().valid("all", "down", "resolve"), filter: joi.string().valid("all", "down", "resolve"),
page: joi.number(), page: joi.number(),
rowsPerPage: joi.number(), rowsPerPage: joi.number(),
}); });
const deleteChecksParamValidation = joi.object({ const deleteChecksParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
const deleteChecksByTeamIdParamValidation = joi.object({ const deleteChecksByTeamIdParamValidation = joi.object({
teamId: joi.string().required(), teamId: joi.string().required(),
}); });
const updateChecksTTLBodyValidation = joi.object({ const updateChecksTTLBodyValidation = joi.object({
ttl: joi.number().required(), ttl: joi.number().required(),
}); });
//**************************************** //****************************************
@@ -340,21 +340,21 @@ const updateChecksTTLBodyValidation = joi.object({
//**************************************** //****************************************
const getPageSpeedCheckParamValidation = joi.object({ const getPageSpeedCheckParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
//Validation schema for the monitorId parameter //Validation schema for the monitorId parameter
const createPageSpeedCheckParamValidation = joi.object({ const createPageSpeedCheckParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
//Validation schema for the monitorId body //Validation schema for the monitorId body
const createPageSpeedCheckBodyValidation = joi.object({ const createPageSpeedCheckBodyValidation = joi.object({
url: joi.string().required(), url: joi.string().required(),
}); });
const deletePageSpeedCheckParamValidation = joi.object({ const deletePageSpeedCheckParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
//**************************************** //****************************************
@@ -362,120 +362,120 @@ const deletePageSpeedCheckParamValidation = joi.object({
//**************************************** //****************************************
const createMaintenanceWindowBodyValidation = joi.object({ const createMaintenanceWindowBodyValidation = joi.object({
monitors: joi.array().items(joi.string()).required(), monitors: joi.array().items(joi.string()).required(),
name: joi.string().required(), name: joi.string().required(),
active: joi.boolean(), active: joi.boolean(),
start: joi.date().required(), start: joi.date().required(),
end: joi.date().required(), end: joi.date().required(),
repeat: joi.number().required(), repeat: joi.number().required(),
expiry: joi.date(), expiry: joi.date(),
}); });
const getMaintenanceWindowByIdParamValidation = joi.object({ const getMaintenanceWindowByIdParamValidation = joi.object({
id: joi.string().required(), id: joi.string().required(),
}); });
const getMaintenanceWindowsByTeamIdQueryValidation = joi.object({ const getMaintenanceWindowsByTeamIdQueryValidation = joi.object({
active: joi.boolean(), active: joi.boolean(),
page: joi.number(), page: joi.number(),
rowsPerPage: joi.number(), rowsPerPage: joi.number(),
field: joi.string(), field: joi.string(),
order: joi.string().valid("asc", "desc"), order: joi.string().valid("asc", "desc"),
}); });
const getMaintenanceWindowsByMonitorIdParamValidation = joi.object({ const getMaintenanceWindowsByMonitorIdParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
const deleteMaintenanceWindowByIdParamValidation = joi.object({ const deleteMaintenanceWindowByIdParamValidation = joi.object({
id: joi.string().required(), id: joi.string().required(),
}); });
const editMaintenanceWindowByIdParamValidation = joi.object({ const editMaintenanceWindowByIdParamValidation = joi.object({
id: joi.string().required(), id: joi.string().required(),
}); });
const editMaintenanceByIdWindowBodyValidation = joi.object({ const editMaintenanceByIdWindowBodyValidation = joi.object({
active: joi.boolean(), active: joi.boolean(),
name: joi.string(), name: joi.string(),
repeat: joi.number(), repeat: joi.number(),
start: joi.date(), start: joi.date(),
end: joi.date(), end: joi.date(),
expiry: joi.date(), expiry: joi.date(),
monitors: joi.array(), monitors: joi.array(),
}); });
//**************************************** //****************************************
// SettingsValidation // SettingsValidation
//**************************************** //****************************************
const updateAppSettingsBodyValidation = joi.object({ const updateAppSettingsBodyValidation = joi.object({
apiBaseUrl: joi.string().allow(""), apiBaseUrl: joi.string().allow(""),
logLevel: joi.string().valid("debug", "none", "error", "warn").allow(""), logLevel: joi.string().valid("debug", "none", "error", "warn").allow(""),
clientHost: joi.string().allow(""), clientHost: joi.string().allow(""),
dbType: joi.string().allow(""), dbType: joi.string().allow(""),
dbConnectionString: joi.string().allow(""), dbConnectionString: joi.string().allow(""),
redisHost: joi.string().allow(""), redisHost: joi.string().allow(""),
redisPort: joi.number().allow(null, ""), redisPort: joi.number().allow(null, ""),
jwtTTL: joi.string().allow(""), jwtTTL: joi.string().allow(""),
pagespeedApiKey: joi.string().allow(""), pagespeedApiKey: joi.string().allow(""),
systemEmailHost: joi.string().allow(""), systemEmailHost: joi.string().allow(""),
systemEmailPort: joi.number().allow(""), systemEmailPort: joi.number().allow(""),
systemEmailAddress: joi.string().allow(""), systemEmailAddress: joi.string().allow(""),
systemEmailPassword: joi.string().allow(""), systemEmailPassword: joi.string().allow(""),
}); });
export { export {
roleValidatior, roleValidatior,
loginValidation, loginValidation,
registrationBodyValidation, registrationBodyValidation,
recoveryValidation, recoveryValidation,
recoveryTokenValidation, recoveryTokenValidation,
newPasswordValidation, newPasswordValidation,
inviteRoleValidation, inviteRoleValidation,
inviteBodyValidation, inviteBodyValidation,
inviteVerificationBodyValidation, inviteVerificationBodyValidation,
createMonitorBodyValidation, createMonitorBodyValidation,
getMonitorByIdParamValidation, getMonitorByIdParamValidation,
getMonitorByIdQueryValidation, getMonitorByIdQueryValidation,
getMonitorsAndSummaryByTeamIdParamValidation, getMonitorsAndSummaryByTeamIdParamValidation,
getMonitorsAndSummaryByTeamIdQueryValidation, getMonitorsAndSummaryByTeamIdQueryValidation,
getMonitorsByTeamIdValidation, getMonitorsByTeamIdValidation,
getMonitorsByTeamIdQueryValidation, getMonitorsByTeamIdQueryValidation,
getMonitorStatsByIdParamValidation, getMonitorStatsByIdParamValidation,
getMonitorStatsByIdQueryValidation, getMonitorStatsByIdQueryValidation,
getCertificateParamValidation, getCertificateParamValidation,
editMonitorBodyValidation, editMonitorBodyValidation,
pauseMonitorParamValidation, pauseMonitorParamValidation,
editUserParamValidation, editUserParamValidation,
editUserBodyValidation, editUserBodyValidation,
createAlertParamValidation, createAlertParamValidation,
createAlertBodyValidation, createAlertBodyValidation,
getAlertsByUserIdParamValidation, getAlertsByUserIdParamValidation,
getAlertsByMonitorIdParamValidation, getAlertsByMonitorIdParamValidation,
getAlertByIdParamValidation, getAlertByIdParamValidation,
editAlertParamValidation, editAlertParamValidation,
editAlertBodyValidation, editAlertBodyValidation,
deleteAlertParamValidation, deleteAlertParamValidation,
createCheckParamValidation, createCheckParamValidation,
createCheckBodyValidation, createCheckBodyValidation,
getChecksParamValidation, getChecksParamValidation,
getChecksQueryValidation, getChecksQueryValidation,
getTeamChecksParamValidation, getTeamChecksParamValidation,
getTeamChecksQueryValidation, getTeamChecksQueryValidation,
deleteChecksParamValidation, deleteChecksParamValidation,
deleteChecksByTeamIdParamValidation, deleteChecksByTeamIdParamValidation,
updateChecksTTLBodyValidation, updateChecksTTLBodyValidation,
deleteUserParamValidation, deleteUserParamValidation,
getPageSpeedCheckParamValidation, getPageSpeedCheckParamValidation,
createPageSpeedCheckParamValidation, createPageSpeedCheckParamValidation,
deletePageSpeedCheckParamValidation, deletePageSpeedCheckParamValidation,
createPageSpeedCheckBodyValidation, createPageSpeedCheckBodyValidation,
createMaintenanceWindowBodyValidation, createMaintenanceWindowBodyValidation,
getMaintenanceWindowByIdParamValidation, getMaintenanceWindowByIdParamValidation,
getMaintenanceWindowsByTeamIdQueryValidation, getMaintenanceWindowsByTeamIdQueryValidation,
getMaintenanceWindowsByMonitorIdParamValidation, getMaintenanceWindowsByMonitorIdParamValidation,
deleteMaintenanceWindowByIdParamValidation, deleteMaintenanceWindowByIdParamValidation,
editMaintenanceWindowByIdParamValidation, editMaintenanceWindowByIdParamValidation,
editMaintenanceByIdWindowBodyValidation, editMaintenanceByIdWindowBodyValidation,
updateAppSettingsBodyValidation, updateAppSettingsBodyValidation,
}; };