Merge branch 'develop' into feat/fallback-refactor

This commit is contained in:
karenvicent committed 2025-07-21 16:19:49 -04:00
commit a28a8fe5f9
97 files changed
+810 -1574

No files matched your search

+9 -3
View File
@@ -72,14 +72,20 @@ You can see the memory footprint of MongoDB and Redis on the same server (398Mb
## 💚 Questions & Ideas ## 💚 Questions & Ideas
If you have any questions, suggestions or comments, please use our [Discord channel](https://discord.gg/NAb6H3UTjK). We've also launched our [Discussions](https://github.com/bluewave-labs/bluewave-uptime/discussions) page! Feel free to ask questions or share your ideas—we'd love to hear from you! If you have any questions, suggestions or comments, you have several options:
- [Discord channel](https://discord.gg/NAb6H3UTjK)
- [GitHub Discussions](https://github.com/bluewave-labs/bluewave-uptime/discussions)
- [Reddit group](https://www.reddit.com/r/CheckmateMonitoring/)
Feel free to ask questions or share your ideas - we'd love to hear from you!
## 🧩 Features ## 🧩 Features
- Completely open source, deployable on your servers or home devices (e.g Raspberry Pi 4 or 5) - Completely open source, deployable on your servers or home devices (e.g Raspberry Pi 4 or 5)
- Website monitoring - Website monitoring
- Page speed monitoring - Page speed monitoring
- Infrastructure monitoring (memory, disk usage, CPU performance etc) - requires [Capture](https://github.com/bluewave-labs/capture) - Infrastructure monitoring (memory, disk usage, CPU performance etc) - requires [Capture](https://github.com/bluewave-labs/capture) agent
- Docker monitoring - Docker monitoring
- Ping monitoring - Ping monitoring
- SSL monitoring - SSL monitoring
@@ -134,7 +140,7 @@ If you have any questions, suggestions or comments, please use our [Discord chan
We are [Alex](http://github.com/ajhollid) (team lead), [Vishnu](http://github.com/vishnusn77), [Mohadeseh](http://github.com/mohicody), [Gorkem](http://github.com/gorkem-bwl/), [Owaise](http://github.com/Owaiseimdad), [Aryaman](https://github.com/Br0wnHammer) and [Mert](https://github.com/mertssmnoglu) helping individuals and businesses monitor their infra and servers. We are [Alex](http://github.com/ajhollid) (team lead), [Vishnu](http://github.com/vishnusn77), [Mohadeseh](http://github.com/mohicody), [Gorkem](http://github.com/gorkem-bwl/), [Owaise](http://github.com/Owaiseimdad), [Aryaman](https://github.com/Br0wnHammer) and [Mert](https://github.com/mertssmnoglu) helping individuals and businesses monitor their infra and servers.
We pride ourselves on building strong connections with contributors at every level. Despite being a young project, Checkmate has already earned 6000+ stars and attracted 80+ contributors from around the globe. We pride ourselves on building strong connections with contributors at every level. Despite being a young project, Checkmate has already earned 7000+ stars and attracted 90+ contributors from around the globe.
Our repo is starred by employees from **Google, Microsoft, Intel, Cisco, Tencent, Electronic Arts, ByteDance, JP Morgan Chase, Deloitte, Accenture, Foxconn, Broadcom, China Telecom, Barclays, Capgemini, Wipro, Cloudflare, Dassault Systèmes and NEC**, so don’t hold back — jump in, contribute and learn with us! Our repo is starred by employees from **Google, Microsoft, Intel, Cisco, Tencent, Electronic Arts, ByteDance, JP Morgan Chase, Deloitte, Accenture, Foxconn, Broadcom, China Telecom, Barclays, Capgemini, Wipro, Cloudflare, Dassault Systèmes and NEC**, so don’t hold back — jump in, contribute and learn with us!
+34
View File
@@ -0,0 +1,34 @@
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { useTheme } from "@emotion/react";
import PropTypes from "prop-types";
const ToastBody = ({ body }) => {
const theme = useTheme();
if (Array.isArray(body)) {
return (
<Stack gap={theme.spacing(2)}>
{body.map((item, idx) => (
<Typography
key={`item-${idx}`}
color={theme.palette.secondary.contrastText}
>
{item}
</Typography>
))}
</Stack>
);
} else if (typeof body === "string") {
return <Typography color={theme.palette.secondary.contrastText}>{body}</Typography>;
}
return null;
};
ToastBody.propTypes = {
body: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
};
export default ToastBody;
+96
View File
@@ -0,0 +1,96 @@
import Stack from "@mui/material/Stack";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import Button from "@mui/material/Button";
import ToastBody from "./body";
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
import ErrorOutlineOutlinedIcon from "@mui/icons-material/ErrorOutlineOutlined";
import WarningAmberOutlinedIcon from "@mui/icons-material/WarningAmberOutlined";
import CloseIcon from "@mui/icons-material/Close";
// Utils
import { useTheme } from "@emotion/react";
import PropTypes from "prop-types";
const icons = {
info: <InfoOutlinedIcon />,
error: <ErrorOutlineOutlinedIcon />,
warning: <WarningAmberOutlinedIcon />,
};
const Toast = ({ variant, title, body, onClick, hasDismiss, hasIcon }) => {
const theme = useTheme();
const icon = icons[variant];
return (
<Stack
gap={theme.spacing(2)}
paddingTop={theme.spacing(4)}
paddingRight={theme.spacing(8)}
paddingBottom={theme.spacing(4)}
paddingLeft={theme.spacing(8)}
backgroundColor={theme.palette.alert.main}
border={`solid 1px ${theme.palette.alert.contrastText}`}
borderRadius={theme.shape.borderRadius}
>
<Stack
direction="row"
gap={theme.spacing(8)}
justifyContent="space-between"
alignItems="center"
>
{hasIcon && icon}
{title && (
<Typography
fontWeight="700"
color={theme.palette.secondary.contrastText}
>
{title}
</Typography>
)}
{title && (
<IconButton onClick={onClick}>
<CloseIcon />
</IconButton>
)}
</Stack>
<Stack
direction="row"
gap={theme.spacing(2)}
alignItems="center"
>
<ToastBody body={body} />
{!title && (
<IconButton onClick={onClick}>
<CloseIcon />
</IconButton>
)}
</Stack>
{hasDismiss && (
<Button
variant="text"
color="info"
onClick={onClick}
sx={{
fontWeight: "600",
width: "fit-content",
}}
>
Dismiss
</Button>
)}
</Stack>
);
};
export default Toast;
Toast.propTypes = {
variant: PropTypes.string.isRequired,
title: PropTypes.string,
body: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
hasDismiss: PropTypes.bool,
hasIcon: PropTypes.bool,
onClick: PropTypes.func,
};
+1 -5
View File
@@ -44,7 +44,6 @@ export const login = createAsyncThunk("auth/login", async (form, thunkApi) => {
export const update = createAsyncThunk("auth/update", async (data, thunkApi) => { export const update = createAsyncThunk("auth/update", async (data, thunkApi) => {
const { localData: form } = data; const { localData: form } = data;
const user = thunkApi.getState().auth.user;
try { try {
const fd = new FormData(); const fd = new FormData();
form.firstName && fd.append("firstName", form.firstName); form.firstName && fd.append("firstName", form.firstName);
@@ -60,7 +59,6 @@ export const update = createAsyncThunk("auth/update", async (data, thunkApi) =>
form.deleteProfileImage && fd.append("deleteProfileImage", form.deleteProfileImage); form.deleteProfileImage && fd.append("deleteProfileImage", form.deleteProfileImage);
const res = await networkService.updateUser({ const res = await networkService.updateUser({
userId: user._id,
form: fd, form: fd,
}); });
return res.data; return res.data;
@@ -77,10 +75,8 @@ export const update = createAsyncThunk("auth/update", async (data, thunkApi) =>
}); });
export const deleteUser = createAsyncThunk("auth/delete", async (_, thunkApi) => { export const deleteUser = createAsyncThunk("auth/delete", async (_, thunkApi) => {
const user = thunkApi.getState().auth.user;
try { try {
const res = await networkService.deleteUser({ userId: user._id }); const res = await networkService.deleteUser();
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
+3 -3
View File
@@ -393,7 +393,7 @@ class NetworkService {
* *
*/ */
async updateUser(config) { async updateUser(config) {
return this.axiosInstance.put(`/auth/user/${config.userId}`, config.form); return this.axiosInstance.put(`/auth/user`, config.form);
} }
/** /**
@@ -406,8 +406,8 @@ class NetworkService {
* @param {string} config.userId - The ID of the user to be deleted. * @param {string} config.userId - The ID of the user to be deleted.
* *
**/ **/
async deleteUser(config) { async deleteUser() {
return this.axiosInstance.delete(`/auth/user/${config.userId}`); return this.axiosInstance.delete(`/auth/user`);
} }
/** /**
+6 -4
View File
@@ -1,7 +1,6 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { toast, Slide } from "react-toastify"; import { toast, Slide } from "react-toastify";
import Alert from "../Components/Alert"; import Toast from "../Components/Toast";
/** /**
* @param {object} props * @param {object} props
* @param {'info' | 'error' | 'warning'} - The variant of the alert (e.g., "info", "error"). * @param {'info' | 'error' | 'warning'} - The variant of the alert (e.g., "info", "error").
@@ -15,6 +14,7 @@ export const createToast = ({
variant = "info", variant = "info",
title, title,
body, body,
hasDismiss = false,
hasIcon = false, hasIcon = false,
config = {}, config = {},
}) => { }) => {
@@ -29,13 +29,14 @@ export const createToast = ({
toast( toast(
({ closeToast }) => ( ({ closeToast }) => (
<Alert <Toast
variant={variant} variant={variant}
title={title} title={title}
body={body} body={body}
isToast={true} isToast={true}
hasIcon={hasIcon}
onClick={closeToast} onClick={closeToast}
hasDismiss={hasDismiss}
hasIcon={hasIcon}
/> />
), ),
toastConfig toastConfig
@@ -47,5 +48,6 @@ createToast.propTypes = {
title: PropTypes.string, title: PropTypes.string,
body: PropTypes.string.isRequired, body: PropTypes.string.isRequired,
hasIcon: PropTypes.bool, hasIcon: PropTypes.bool,
hasDismiss: PropTypes.bool,
config: PropTypes.object, config: PropTypes.object,
}; };
+1 -1
View File
@@ -1,5 +1,5 @@
{ {
"printWidth": 90, "printWidth": 150,
"useTabs": true, "useTabs": true,
"tabWidth": 2, "tabWidth": 2,
"singleQuote": false, "singleQuote": false,
+30 -32
View File
@@ -1,7 +1,6 @@
import { import {
registrationBodyValidation, registrationBodyValidation,
loginValidation, loginValidation,
editUserParamValidation,
editUserBodyValidation, editUserBodyValidation,
recoveryValidation, recoveryValidation,
recoveryTokenValidation, recoveryTokenValidation,
@@ -91,16 +90,14 @@ class AuthController {
const html = await this.emailService.buildEmail("welcomeEmailTemplate", { const html = await this.emailService.buildEmail("welcomeEmailTemplate", {
name: newUser.firstName, name: newUser.firstName,
}); });
this.emailService this.emailService.sendEmail(newUser.email, "Welcome to Uptime Monitor", html).catch((error) => {
.sendEmail(newUser.email, "Welcome to Uptime Monitor", html) this.logger.warn({
.catch((error) => { message: error.message,
this.logger.warn({ service: SERVICE_NAME,
message: error.message, method: "registerUser",
service: SERVICE_NAME, stack: error.stack,
method: "registerUser",
stack: error.stack,
});
}); });
});
} catch (error) { } catch (error) {
this.logger.warn({ this.logger.warn({
message: error.message, message: error.message,
@@ -188,14 +185,8 @@ class AuthController {
*/ */
editUser = asyncHandler( editUser = asyncHandler(
async (req, res, next) => { async (req, res, next) => {
await editUserParamValidation.validateAsync(req.params);
await editUserBodyValidation.validateAsync(req.body); await editUserBodyValidation.validateAsync(req.body);
// TODO is this neccessary any longer? Verify ownership middleware should handle this
if (req.params.userId !== req.user._id.toString()) {
throw createAuthError(this.stringService.unauthorized);
}
// Change Password check // Change Password check
if (req.body.password && req.body.newPassword) { if (req.body.password && req.body.newPassword) {
// Get token from headers // Get token from headers
@@ -218,7 +209,7 @@ class AuthController {
req.body.password = req.body.newPassword; req.body.password = req.body.newPassword;
} }
const updatedUser = await this.db.updateUser(req, res); const updatedUser = await this.db.updateUser({ userId: req?.user?._id, user: req.body, file: req.file });
res.success({ res.success({
msg: this.stringService.authUpdateUser, msg: this.stringService.authUpdateUser,
data: updatedUser, data: updatedUser,
@@ -274,11 +265,7 @@ class AuthController {
email, email,
url, url,
}); });
const msgId = await this.emailService.sendEmail( const msgId = await this.emailService.sendEmail(email, "Checkmate Password Reset", html);
email,
"Checkmate Password Reset",
html
);
return res.success({ return res.success({
msg: this.stringService.authCreateRecoveryToken, msg: this.stringService.authCreateRecoveryToken,
@@ -349,20 +336,31 @@ class AuthController {
*/ */
deleteUser = asyncHandler( deleteUser = asyncHandler(
async (req, res, next) => { async (req, res, next) => {
const token = getTokenFromHeaders(req.headers); const email = req?.user?.email;
const decodedToken = jwt.decode(token); if (!email) {
const { email } = decodedToken; throw new Error("No email in request");
}
// Check if the user exists
const user = await this.db.getUserByEmail(email);
// 1. Find all the monitors associated with the team ID if superadmin // 1. Find all the monitors associated with the team ID if superadmin
const teamId = req?.user?.teamId;
const userId = req?.user?._id;
if (!teamId) {
throw new Error("No team ID in request");
}
if (!userId) {
throw new Error("No user ID in request");
}
const roles = req.user.role;
const result = await this.db.getMonitorsByTeamId({ const result = await this.db.getMonitorsByTeamId({
teamId: user.teamId.toString(), teamId: teamId,
}); });
if (user.role.includes("superadmin")) { if (roles.includes("superadmin")) {
//2. Remove all jobs, delete checks and alerts // 2. Remove all jobs, delete checks and alerts
result?.monitors.length > 0 && result?.monitors.length > 0 &&
(await Promise.all( (await Promise.all(
result.monitors.map(async (monitor) => { result.monitors.map(async (monitor) => {
@@ -371,7 +369,7 @@ class AuthController {
)); ));
} }
// 6. Delete the user by id // 6. Delete the user by id
await this.db.deleteUser(user._id); await this.db.deleteUser(userId);
return res.success({ return res.success({
msg: this.stringService.authDeleteUser, msg: this.stringService.authDeleteUser,
+115 -31
View File
@@ -1,6 +1,4 @@
import { import {
createCheckParamValidation,
createCheckBodyValidation,
getChecksParamValidation, getChecksParamValidation,
getChecksQueryValidation, getChecksQueryValidation,
getTeamChecksParamValidation, getTeamChecksParamValidation,
@@ -23,31 +21,41 @@ class CheckController {
this.stringService = stringService; this.stringService = stringService;
} }
createCheck = asyncHandler(
async (req, res, next) => {
await createCheckParamValidation.validateAsync(req.params);
await createCheckBodyValidation.validateAsync(req.body);
const checkData = { ...req.body };
const check = await this.db.createCheck(checkData);
return res.success({
msg: this.stringService.checkCreate,
data: check,
});
},
SERVICE_NAME,
"createCheck"
);
getChecksByMonitor = asyncHandler( getChecksByMonitor = asyncHandler(
async (req, res, next) => { async (req, res, next) => {
await getChecksParamValidation.validateAsync(req.params); await getChecksParamValidation.validateAsync(req.params);
await getChecksQueryValidation.validateAsync(req.query); await getChecksQueryValidation.validateAsync(req.query);
const { monitorId } = req.params; const monitorId = req?.params?.monitorId;
let { type, sortOrder, dateRange, filter, ack, page, rowsPerPage, status } =
req.query; if (!monitorId) {
throw new Error("No monitor ID in request");
}
const teamId = req?.user?.teamId;
if (!teamId) {
throw new Error("No team ID in request");
}
const monitor = await this.db.getMonitorById(monitorId);
if (!monitor) {
const err = new Error("Monitor not found");
err.status = 404;
err.service = SERVICE_NAME;
err.method = "getChecksByMonitor";
throw err;
}
if (!monitor.teamId.equals(teamId)) {
const err = new Error("Unauthorized");
err.status = 403;
err.service = SERVICE_NAME;
err.method = "getChecksByMonitor";
throw err;
}
let { type, sortOrder, dateRange, filter, ack, page, rowsPerPage, status } = req.query;
const result = await this.db.getChecksByMonitor({ const result = await this.db.getChecksByMonitor({
monitorId, monitorId,
type, type,
@@ -75,7 +83,11 @@ class CheckController {
await getTeamChecksQueryValidation.validateAsync(req.query); await getTeamChecksQueryValidation.validateAsync(req.query);
let { sortOrder, dateRange, filter, ack, page, rowsPerPage } = req.query; let { sortOrder, dateRange, filter, ack, page, rowsPerPage } = req.query;
const { teamId } = req.user; const teamId = req?.user?.teamId;
if (!teamId) {
throw new Error("No team ID in request");
}
const checkData = await this.db.getChecksByTeam({ const checkData = await this.db.getChecksByTeam({
sortOrder, sortOrder,
@@ -97,7 +109,12 @@ class CheckController {
getChecksSummaryByTeamId = asyncHandler( getChecksSummaryByTeamId = asyncHandler(
async (req, res, next) => { async (req, res, next) => {
const { teamId } = req.user; const teamId = req?.user?.teamId;
if (!teamId) {
throw new Error("No team ID in request");
}
const summary = await this.db.getChecksSummaryByTeamId({ teamId }); const summary = await this.db.getChecksSummaryByTeamId({ teamId });
return res.success({ return res.success({
msg: this.stringService.checkGetSummary, msg: this.stringService.checkGetSummary,
@@ -112,9 +129,17 @@ class CheckController {
async (req, res, next) => { async (req, res, next) => {
await ackCheckBodyValidation.validateAsync(req.body); await ackCheckBodyValidation.validateAsync(req.body);
const { checkId } = req.params; const checkId = req?.params?.checkId;
const { ack } = req.body; const ack = req?.body?.ack;
const { teamId } = req.user; const teamId = req?.user?.teamId;
if (!checkId) {
throw new Error("No check ID in request");
}
if (!teamId) {
throw new Error("No team ID in request");
}
const updatedCheck = await this.db.ackCheck(checkId, teamId, ack); const updatedCheck = await this.db.ackCheck(checkId, teamId, ack);
@@ -132,9 +157,35 @@ class CheckController {
await ackAllChecksParamValidation.validateAsync(req.params); await ackAllChecksParamValidation.validateAsync(req.params);
await ackAllChecksBodyValidation.validateAsync(req.body); await ackAllChecksBodyValidation.validateAsync(req.body);
const { monitorId, path } = req.params; const teamId = req?.user?.teamId;
const { ack } = req.body; if (!teamId) {
const { teamId } = req.user; throw new Error("No team ID in request");
}
const monitorId = req?.params?.monitorId;
const path = req?.params?.path;
const ack = req?.body?.ack;
if (path === "monitor") {
if (!monitorId) {
throw new Error("No monitor ID in request");
}
const monitor = await this.db.getMonitorById(monitorId);
if (!monitor) {
throw new Error("Monitor not found");
}
if (!monitor.teamId.equals(teamId)) {
const err = new Error("Unauthorized");
err.status = 403;
err.service = SERVICE_NAME;
err.method = "ackAllChecks";
throw err;
}
}
const updatedChecks = await this.db.ackAllChecks(monitorId, teamId, ack, path); const updatedChecks = await this.db.ackAllChecks(monitorId, teamId, ack, path);
@@ -151,6 +202,35 @@ class CheckController {
async (req, res, next) => { async (req, res, next) => {
await deleteChecksParamValidation.validateAsync(req.params); await deleteChecksParamValidation.validateAsync(req.params);
const monitorId = req?.params?.monitorId;
const teamId = req?.user?.teamId;
if (!monitorId) {
throw new Error("No monitor ID in request");
}
if (!teamId) {
throw new Error("No team ID in request");
}
const monitor = await this.db.getMonitorById(monitorId);
if (!monitor) {
const err = new Error("Monitor not found");
err.status = 404;
err.service = SERVICE_NAME;
err.method = "deleteChecks";
throw err;
}
if (!monitor.teamId.equals(teamId)) {
const err = new Error("Unauthorized");
err.status = 403;
err.service = SERVICE_NAME;
err.method = "deleteChecks";
throw err;
}
const deletedCount = await this.db.deleteChecks(req.params.monitorId); const deletedCount = await this.db.deleteChecks(req.params.monitorId);
return res.success({ return res.success({
@@ -166,7 +246,11 @@ class CheckController {
async (req, res, next) => { async (req, res, next) => {
await deleteChecksByTeamIdParamValidation.validateAsync(req.params); await deleteChecksByTeamIdParamValidation.validateAsync(req.params);
const { teamId } = req.user; const teamId = req?.user?.teamId;
if (!teamId) {
throw new Error("No team ID in request");
}
const deletedCount = await this.db.deleteChecksByTeamId(teamId); const deletedCount = await this.db.deleteChecksByTeamId(teamId);
return res.success({ return res.success({
+12 -55
View File
@@ -12,63 +12,20 @@ obs.observe({ entryTypes: ["measure"] });
class DiagnosticController { class DiagnosticController {
constructor(db) { constructor(db) {
this.db = db; this.db = db;
this.getMonitorsByTeamIdExecutionStats =
this.getMonitorsByTeamIdExecutionStats.bind(this);
this.getDbStats = this.getDbStats.bind(this);
} }
getMonitorsByTeamIdExecutionStats = asyncHandler( getCPUUsage = async () => {
async (req, res, next) => { const startUsage = process.cpuUsage();
const data = await this.db.getMonitorsByTeamIdExecutionStats(req); const timingPeriod = 1000; // measured in ms
return res.success({ await new Promise((resolve) => setTimeout(resolve, timingPeriod));
msg: "OK", const endUsage = process.cpuUsage(startUsage);
data, const cpuUsage = {
}); userUsageMs: endUsage.user / 1000,
}, systemUsageMs: endUsage.system / 1000,
SERVICE_NAME, usagePercentage: ((endUsage.user + endUsage.system) / 1000 / timingPeriod) * 100,
"getMonitorsByTeamIdExecutionStats" };
); return cpuUsage;
};
getDbStats = asyncHandler(
async (req, res, next) => {
const { methodName, args = [] } = req.body;
if (!methodName || !this.db[methodName]) {
return res.error({
msg: "Invalid method name or method doesn't exist",
status: 400,
});
}
const explainMethod = await this.db[methodName].apply(this.db, args);
const stats = {
methodName,
timestamp: new Date(),
explain: explainMethod,
};
return res.success({
msg: "OK",
data: stats,
});
},
SERVICE_NAME,
"getDbStats"
);
getCPUUsage = asyncHandler(
async (req, res, next) => {
const startUsage = process.cpuUsage();
const timingPeriod = 1000; // measured in ms
await new Promise((resolve) => setTimeout(resolve, timingPeriod));
const endUsage = process.cpuUsage(startUsage);
const cpuUsage = {
userUsageMs: endUsage.user / 1000,
systemUsageMs: endUsage.system / 1000,
usagePercentage: ((endUsage.user + endUsage.system) / 1000 / timingPeriod) * 100,
};
return cpuUsage;
},
SERVICE_NAME,
"getCPUUsage"
);
getSystemStats = asyncHandler( getSystemStats = asyncHandler(
async (req, res, next) => { async (req, res, next) => {
+3 -13
View File
@@ -1,8 +1,4 @@
import { import { inviteRoleValidation, inviteBodyValidation, inviteVerificationBodyValidation } from "../validation/joi.js";
inviteRoleValidation,
inviteBodyValidation,
inviteVerificationBodyValidation,
} from "../validation/joi.js";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import { getTokenFromHeaders } from "../utils/utils.js"; import { getTokenFromHeaders } from "../utils/utils.js";
import { asyncHandler, createServerError } from "../utils/errorUtils.js"; import { asyncHandler, createServerError } from "../utils/errorUtils.js";
@@ -65,15 +61,9 @@ class InviteController {
name: firstname, name: firstname,
link: `${clientHost}/register/${inviteToken.token}`, link: `${clientHost}/register/${inviteToken.token}`,
}); });
const result = await this.emailService.sendEmail( const result = await this.emailService.sendEmail(req.body.email, "Welcome to Uptime Monitor", html);
req.body.email,
"Welcome to Uptime Monitor",
html
);
if (!result) { if (!result) {
throw createServerError( throw createServerError("Failed to send invite e-mail... Please verify your settings.");
"Failed to send invite e-mail... Please verify your settings."
);
} }
return res.success({ return res.success({
@@ -22,8 +22,25 @@ class MaintenanceWindowController {
async (req, res, next) => { async (req, res, next) => {
await createMaintenanceWindowBodyValidation.validateAsync(req.body); await createMaintenanceWindowBodyValidation.validateAsync(req.body);
const { teamId } = req.user; const teamId = req?.user?.teamId;
if (!teamId) {
throw new Error("Team ID is required");
}
const monitorIds = req.body.monitors; const monitorIds = req.body.monitors;
const monitors = await this.db.getMonitorsByIds(monitorIds);
const unauthorizedMonitors = monitors.filter((monitor) => !monitor.teamId.equals(teamId));
if (unauthorizedMonitors.length > 0) {
const error = new Error("Unauthorized access to one or more monitors");
error.status = 403;
error.service = SERVICE_NAME;
error.method = "createMaintenanceWindows";
throw error;
}
const dbTransactions = monitorIds.map((monitorId) => { const dbTransactions = monitorIds.map((monitorId) => {
return this.db.createMaintenanceWindow({ return this.db.createMaintenanceWindow({
teamId, teamId,
@@ -48,7 +65,13 @@ class MaintenanceWindowController {
getMaintenanceWindowById = asyncHandler( getMaintenanceWindowById = asyncHandler(
async (req, res, next) => { async (req, res, next) => {
await getMaintenanceWindowByIdParamValidation.validateAsync(req.params); await getMaintenanceWindowByIdParamValidation.validateAsync(req.params);
const maintenanceWindow = await this.db.getMaintenanceWindowById(req.params.id);
const teamId = req.user.teamId;
if (!teamId) {
throw new Error("Team ID is required");
}
const maintenanceWindow = await this.db.getMaintenanceWindowById({ id: req.params.id, teamId });
return res.success({ return res.success({
msg: this.stringService.maintenanceWindowGetById, msg: this.stringService.maintenanceWindowGetById,
data: maintenanceWindow, data: maintenanceWindow,
@@ -62,11 +85,13 @@ class MaintenanceWindowController {
async (req, res, next) => { async (req, res, next) => {
await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query); await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query);
const { teamId } = req.user; const teamId = req?.user?.teamId;
const maintenanceWindows = await this.db.getMaintenanceWindowsByTeamId(
teamId, if (!teamId) {
req.query throw new Error("Team ID is required");
); }
const maintenanceWindows = await this.db.getMaintenanceWindowsByTeamId(teamId, req.query);
return res.success({ return res.success({
msg: this.stringService.maintenanceWindowGetByTeam, msg: this.stringService.maintenanceWindowGetByTeam,
@@ -81,9 +106,14 @@ class MaintenanceWindowController {
async (req, res, next) => { async (req, res, next) => {
await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync(req.params); await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync(req.params);
const maintenanceWindows = await this.db.getMaintenanceWindowsByMonitorId( const monitorId = req.params.monitorId;
req.params.monitorId
); const teamId = req?.user?.teamId;
if (!teamId) {
throw new Error("Team ID is required");
}
const maintenanceWindows = await this.db.getMaintenanceWindowsByMonitorId({ monitorId, teamId });
return res.success({ return res.success({
msg: this.stringService.maintenanceWindowGetByUser, msg: this.stringService.maintenanceWindowGetByUser,
@@ -97,7 +127,13 @@ class MaintenanceWindowController {
deleteMaintenanceWindow = asyncHandler( deleteMaintenanceWindow = asyncHandler(
async (req, res, next) => { async (req, res, next) => {
await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params); await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params);
await this.db.deleteMaintenanceWindowById(req.params.id);
const teamId = req?.user?.teamId;
if (!teamId) {
throw new Error("Team ID is required");
}
await this.db.deleteMaintenanceWindowById({ id: req.params.id, teamId });
return res.success({ return res.success({
msg: this.stringService.maintenanceWindowDelete, msg: this.stringService.maintenanceWindowDelete,
}); });
@@ -110,10 +146,14 @@ class MaintenanceWindowController {
async (req, res, next) => { async (req, res, next) => {
await editMaintenanceWindowByIdParamValidation.validateAsync(req.params); await editMaintenanceWindowByIdParamValidation.validateAsync(req.params);
await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body); await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body);
const editedMaintenanceWindow = await this.db.editMaintenanceWindowById(
req.params.id, const teamId = req.user.teamId;
req.body if (!teamId) {
); throw new Error("Team ID is required");
}
const editedMaintenanceWindow = await this.db.editMaintenanceWindowById({ id: req.params.id, body: req.body, teamId });
return res.success({ return res.success({
msg: this.stringService.maintenanceWindowEdit, msg: this.stringService.maintenanceWindowEdit,
data: editedMaintenanceWindow, data: editedMaintenanceWindow,
+3 -9
View File
@@ -463,14 +463,10 @@ class MonitorController {
const monitorId = req.params.monitorId; const monitorId = req.params.monitorId;
const monitor = await this.db.pauseMonitor({ monitorId }); const monitor = await this.db.pauseMonitor({ monitorId });
monitor.isActive === true monitor.isActive === true ? await this.jobQueue.resumeJob(monitor._id, monitor) : await this.jobQueue.pauseJob(monitor);
? await this.jobQueue.resumeJob(monitor._id, monitor)
: await this.jobQueue.pauseJob(monitor);
return res.success({ return res.success({
msg: monitor.isActive msg: monitor.isActive ? this.stringService.monitorResume : this.stringService.monitorPause,
? this.stringService.monitorResume
: this.stringService.monitorPause,
data: monitor, data: monitor,
}); });
}, },
@@ -493,9 +489,7 @@ class MonitorController {
async (req, res, next) => { async (req, res, next) => {
const { _id, teamId } = req.user; const { _id, teamId } = req.user;
const demoMonitors = await this.db.addDemoMonitors(_id, teamId); const demoMonitors = await this.db.addDemoMonitors(_id, teamId);
await Promise.all( await Promise.all(demoMonitors.map((monitor) => this.jobQueue.addJob(monitor._id, monitor)));
demoMonitors.map((monitor) => this.jobQueue.addJob(monitor._id, monitor))
);
return res.success({ return res.success({
msg: this.stringService.monitorDemoAdded, msg: this.stringService.monitorDemoAdded,
+1 -6
View File
@@ -1,9 +1,4 @@
import { import { createStatusPageBodyValidation, getStatusPageParamValidation, getStatusPageQueryValidation, imageValidation } from "../validation/joi.js";
createStatusPageBodyValidation,
getStatusPageParamValidation,
getStatusPageQueryValidation,
imageValidation,
} from "../validation/joi.js";
import { asyncHandler } from "../utils/errorUtils.js"; import { asyncHandler } from "../utils/errorUtils.js";
const SERVICE_NAME = "statusPageController"; const SERVICE_NAME = "statusPageController";
+1 -4
View File
@@ -156,10 +156,7 @@ MonitorSchema.pre("deleteMany", async function (next) {
} else { } else {
await Check.deleteMany({ monitorId: monitor._id }); await Check.deleteMany({ monitorId: monitor._id });
} }
await StatusPage.updateMany( await StatusPage.updateMany({ monitors: monitor._id }, { $pull: { monitors: monitor._id } });
{ monitors: monitor._id },
{ $pull: { monitors: monitor._id } }
);
await MonitorStats.deleteMany({ monitorId: monitor._id.toString() }); await MonitorStats.deleteMany({ monitorId: monitor._id.toString() });
} }
next(); next();
+1 -2
View File
@@ -89,8 +89,7 @@ class MongoDB {
connect = async () => { connect = async () => {
try { try {
const connectionString = const connectionString = this.appSettings.dbConnectionString || "mongodb://localhost:27017/uptime_db";
this.appSettings.dbConnectionString || "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
await AppSettings.findOneAndUpdate( await AppSettings.findOneAndUpdate(
+7 -40
View File
@@ -58,26 +58,13 @@ const createChecks = async (checks) => {
* @returns {Promise<Array<Check>>} * @returns {Promise<Array<Check>>}
* @throws {Error} * @throws {Error}
*/ */
const getChecksByMonitor = async ({ const getChecksByMonitor = async ({ monitorId, type, sortOrder, dateRange, filter, ack, page, rowsPerPage, status }) => {
monitorId,
type,
sortOrder,
dateRange,
filter,
ack,
page,
rowsPerPage,
status,
}) => {
try { try {
status = status === "true" ? true : status === "false" ? false : undefined; status = status === "true" ? true : status === "false" ? false : undefined;
page = parseInt(page); page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage); rowsPerPage = parseInt(rowsPerPage);
const ackStage = const ackStage = ack === "true" ? { ack: true } : { $or: [{ ack: false }, { ack: { $exists: false } }] };
ack === "true"
? { ack: true }
: { $or: [{ ack: false }, { ack: { $exists: false } }] };
// Match // Match
const matchStage = { const matchStage = {
@@ -158,23 +145,12 @@ const getChecksByMonitor = async ({
} }
}; };
const getChecksByTeam = async ({ const getChecksByTeam = async ({ sortOrder, dateRange, filter, ack, page, rowsPerPage, teamId }) => {
sortOrder,
dateRange,
filter,
ack,
page,
rowsPerPage,
teamId,
}) => {
try { try {
page = parseInt(page); page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage); rowsPerPage = parseInt(rowsPerPage);
const ackStage = const ackStage = ack === "true" ? { ack: true } : { $or: [{ ack: false }, { ack: { $exists: false } }] };
ack === "true"
? { ack: true }
: { $or: [{ ack: false }, { ack: { $exists: false } }] };
const matchStage = { const matchStage = {
teamId: new ObjectId(teamId), teamId: new ObjectId(teamId),
@@ -264,11 +240,7 @@ const getChecksByTeam = async ({
*/ */
const ackCheck = async (checkId, teamId, ack) => { const ackCheck = async (checkId, teamId, ack) => {
try { try {
const updatedCheck = await Check.findOneAndUpdate( const updatedCheck = await Check.findOneAndUpdate({ _id: checkId, teamId: teamId }, { $set: { ack, ackAt: new Date() } }, { new: true });
{ _id: checkId, teamId: teamId },
{ $set: { ack, ackAt: new Date() } },
{ new: true }
);
if (!updatedCheck) { if (!updatedCheck) {
throw new Error("Check not found"); throw new Error("Check not found");
@@ -293,10 +265,7 @@ const ackCheck = async (checkId, teamId, ack) => {
*/ */
const ackAllChecks = async (monitorId, teamId, ack, path) => { const ackAllChecks = async (monitorId, teamId, ack, path) => {
try { try {
const updatedChecks = await Check.updateMany( const updatedChecks = await Check.updateMany(path === "monitor" ? { monitorId } : { teamId }, { $set: { ack, ackAt: new Date() } });
path === "monitor" ? { monitorId } : { teamId },
{ $set: { ack, ackAt: new Date() } }
);
return updatedChecks.modifiedCount; return updatedChecks.modifiedCount;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -317,9 +286,7 @@ const getChecksSummaryByTeamId = async ({ teamId }) => {
const matchStage = { const matchStage = {
teamId: new ObjectId(teamId), teamId: new ObjectId(teamId),
}; };
const checks = await Check.aggregate( const checks = await Check.aggregate(buildChecksSummaryByTeamIdPipeline({ matchStage }));
buildChecksSummaryByTeamIdPipeline({ matchStage })
);
return checks[0].summary; return checks[0].summary;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
+2 -10
View File
@@ -10,20 +10,12 @@ const buildChecksSummaryByTeamIdPipeline = ({ matchStage }) => {
totalChecks: { $sum: { $cond: [{ $eq: ["$status", false] }, 1, 0] } }, totalChecks: { $sum: { $cond: [{ $eq: ["$status", false] }, 1, 0] } },
resolvedChecks: { resolvedChecks: {
$sum: { $sum: {
$cond: [ $cond: [{ $and: [{ $eq: ["$ack", true] }, { $eq: ["$status", false] }] }, 1, 0],
{ $and: [{ $eq: ["$ack", true] }, { $eq: ["$status", false] }] },
1,
0,
],
}, },
}, },
downChecks: { downChecks: {
$sum: { $sum: {
$cond: [ $cond: [{ $and: [{ $eq: ["$ack", false] }, { $eq: ["$status", false] }] }, 1, 0],
{ $and: [{ $eq: ["$ack", false] }, { $eq: ["$status", false] }] },
1,
0,
],
}, },
}, },
cannotResolveChecks: { cannotResolveChecks: {
+3 -11
View File
@@ -2,11 +2,7 @@ import Monitor from "../../models/Monitor.js";
import { ObjectId } from "mongodb"; import { ObjectId } from "mongodb";
const SERVICE_NAME = "diagnosticModule"; const SERVICE_NAME = "diagnosticModule";
import { import { buildMonitorSummaryByTeamIdPipeline, buildMonitorsByTeamIdPipeline, buildFilteredMonitorsByTeamIdPipeline } from "./monitorModuleQueries.js";
buildMonitorSummaryByTeamIdPipeline,
buildMonitorsByTeamIdPipeline,
buildFilteredMonitorsByTeamIdPipeline,
} from "./monitorModuleQueries.js";
const getMonitorsByTeamIdExecutionStats = async (req) => { const getMonitorsByTeamIdExecutionStats = async (req) => {
try { try {
@@ -24,13 +20,9 @@ const getMonitorsByTeamIdExecutionStats = async (req) => {
matchStage.type = Array.isArray(type) ? { $in: type } : type; matchStage.type = Array.isArray(type) ? { $in: type } : type;
} }
const summary = await Monitor.aggregate( const summary = await Monitor.aggregate(buildMonitorSummaryByTeamIdPipeline({ matchStage })).explain("executionStats");
buildMonitorSummaryByTeamIdPipeline({ matchStage })
).explain("executionStats");
const monitors = await Monitor.aggregate( const monitors = await Monitor.aggregate(buildMonitorsByTeamIdPipeline({ matchStage, field, order })).explain("executionStats");
buildMonitorsByTeamIdPipeline({ matchStage, field, order })
).explain("executionStats");
const filteredMonitors = await Monitor.aggregate( const filteredMonitors = await Monitor.aggregate(
buildFilteredMonitorsByTeamIdPipeline({ buildFilteredMonitorsByTeamIdPipeline({
@@ -23,14 +23,10 @@ const createHardwareCheck = async (hardwareCheckData) => {
if (monitor.uptimePercentage === undefined) { if (monitor.uptimePercentage === undefined) {
newUptimePercentage = status === true ? 1 : 0; newUptimePercentage = status === true ? 1 : 0;
} else { } else {
newUptimePercentage = newUptimePercentage = (monitor.uptimePercentage * (n - 1) + (status === true ? 1 : 0)) / n;
(monitor.uptimePercentage * (n - 1) + (status === true ? 1 : 0)) / n;
} }
await Monitor.findOneAndUpdate( await Monitor.findOneAndUpdate({ _id: monitorId }, { uptimePercentage: newUptimePercentage });
{ _id: monitorId },
{ uptimePercentage: newUptimePercentage }
);
const hardwareCheck = await new HardwareCheck({ const hardwareCheck = await new HardwareCheck({
...hardwareCheckData, ...hardwareCheckData,
@@ -34,10 +34,11 @@ const createMaintenanceWindow = async (maintenanceWindowData) => {
} }
}; };
const getMaintenanceWindowById = async (maintenanceWindowId) => { const getMaintenanceWindowById = async ({ id, teamId }) => {
try { try {
const maintenanceWindow = await MaintenanceWindow.findById({ const maintenanceWindow = await MaintenanceWindow.findOne({
_id: maintenanceWindowId, _id: id,
teamId: teamId,
}); });
return maintenanceWindow; return maintenanceWindow;
} catch (error) { } catch (error) {
@@ -63,8 +64,7 @@ const getMaintenanceWindowsByTeamId = async (teamId, query) => {
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;
@@ -78,10 +78,7 @@ const getMaintenanceWindowsByTeamId = async (teamId, query) => {
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).limit(rowsPerPage).sort(sort);
.skip(skip)
.limit(rowsPerPage)
.sort(sort);
return { maintenanceWindows, maintenanceWindowCount }; return { maintenanceWindows, maintenanceWindowCount };
} catch (error) { } catch (error) {
@@ -99,10 +96,11 @@ const getMaintenanceWindowsByTeamId = async (teamId, query) => {
* @returns {Promise<Array<MaintenanceWindow>>} An array of MaintenanceWindow documents. * @returns {Promise<Array<MaintenanceWindow>>} An array of MaintenanceWindow documents.
* @throws {Error} If there is an error retrieving the documents. * @throws {Error} If there is an error retrieving the documents.
*/ */
const getMaintenanceWindowsByMonitorId = async (monitorId) => { const getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }) => {
try { try {
const maintenanceWindows = await MaintenanceWindow.find({ const maintenanceWindows = await MaintenanceWindow.find({
monitorId: monitorId, monitorId: monitorId,
teamId: teamId,
}); });
return maintenanceWindows; return maintenanceWindows;
} catch (error) { } catch (error) {
@@ -120,10 +118,9 @@ const getMaintenanceWindowsByMonitorId = async (monitorId) => {
* @returns {Promise<MaintenanceWindow>} The deleted MaintenanceWindow document. * @returns {Promise<MaintenanceWindow>} The deleted MaintenanceWindow document.
* @throws {Error} If there is an error deleting the document. * @throws {Error} If there is an error deleting the document.
*/ */
const deleteMaintenanceWindowById = async (maintenanceWindowId) => { const deleteMaintenanceWindowById = async ({ id, teamId }) => {
try { try {
const maintenanceWindow = const maintenanceWindow = await MaintenanceWindow.findOneAndDelete({ _id: id, teamId });
await MaintenanceWindow.findByIdAndDelete(maintenanceWindowId);
return maintenanceWindow; return maintenanceWindow;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -172,13 +169,9 @@ const deleteMaintenanceWindowByUserId = async (userId) => {
} }
}; };
const editMaintenanceWindowById = async (maintenanceWindowId, maintenanceWindowData) => { const editMaintenanceWindowById = async ({ id, body, teamId }) => {
try { try {
const editedMaintenanceWindow = await MaintenanceWindow.findByIdAndUpdate( const editedMaintenanceWindow = await MaintenanceWindow.findByIdAndUpdate(id, body, { new: true });
maintenanceWindowId,
maintenanceWindowData,
{ new: true }
);
return editedMaintenanceWindow; return editedMaintenanceWindow;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
+31 -92
View File
@@ -285,10 +285,7 @@ const groupChecksByTime = (checks, dateRange) => {
return acc; return acc;
} }
const time = const time = dateRange === "day" ? checkDate.setMinutes(0, 0, 0) : checkDate.toISOString().split("T")[0];
dateRange === "day"
? checkDate.setMinutes(0, 0, 0)
: checkDate.toISOString().split("T")[0];
if (!acc[time]) { if (!acc[time]) {
acc[time] = { time, checks: [] }; acc[time] = { time, checks: [] };
@@ -306,9 +303,7 @@ const groupChecksByTime = (checks, dateRange) => {
const calculateGroupStats = (group) => { const calculateGroupStats = (group) => {
const totalChecks = group.checks.length; const totalChecks = group.checks.length;
const checksWithResponseTime = group.checks.filter( const checksWithResponseTime = group.checks.filter((check) => typeof check.responseTime === "number" && !Number.isNaN(check.responseTime));
(check) => typeof check.responseTime === "number" && !Number.isNaN(check.responseTime)
);
return { return {
time: group.time, time: group.time,
@@ -317,8 +312,7 @@ const calculateGroupStats = (group) => {
totalIncidents: group.checks.filter((check) => !check.status).length, totalIncidents: group.checks.filter((check) => !check.status).length,
avgResponseTime: avgResponseTime:
checksWithResponseTime.length > 0 checksWithResponseTime.length > 0
? checksWithResponseTime.reduce((sum, check) => sum + check.responseTime, 0) / ? checksWithResponseTime.reduce((sum, check) => sum + check.responseTime, 0) / checksWithResponseTime.length
checksWithResponseTime.length
: 0, : 0,
}; };
}; };
@@ -344,29 +338,15 @@ const getUptimeDetailsById = async ({ monitorId, dateRange, normalize }) => {
const dateString = formatLookup[dateRange]; const dateString = formatLookup[dateRange];
const results = await Check.aggregate( const results = await Check.aggregate(buildUptimeDetailsPipeline(monitorId, dates, dateString));
buildUptimeDetailsPipeline(monitorId, dates, dateString)
);
const monitorData = results[0]; const monitorData = results[0];
monitorData.groupedUpChecks = NormalizeDataUptimeDetails( monitorData.groupedUpChecks = NormalizeDataUptimeDetails(monitorData.groupedUpChecks, 10, 100);
monitorData.groupedUpChecks,
10,
100
);
monitorData.groupedDownChecks = NormalizeDataUptimeDetails( monitorData.groupedDownChecks = NormalizeDataUptimeDetails(monitorData.groupedDownChecks, 10, 100);
monitorData.groupedDownChecks,
10,
100
);
const normalizedGroupChecks = NormalizeDataUptimeDetails( const normalizedGroupChecks = NormalizeDataUptimeDetails(monitorData.groupedChecks, 10, 100);
monitorData.groupedChecks,
10,
100
);
monitorData.groupedChecks = normalizedGroupChecks; monitorData.groupedChecks = normalizedGroupChecks;
const monitorStats = await MonitorStats.findOne({ monitorId }); const monitorStats = await MonitorStats.findOne({ monitorId });
@@ -386,14 +366,7 @@ const getUptimeDetailsById = async ({ monitorId, dateRange, normalize }) => {
* @returns {Promise<Monitor>} * @returns {Promise<Monitor>}
* @throws {Error} * @throws {Error}
*/ */
const getMonitorStatsById = async ({ const getMonitorStatsById = async ({ monitorId, limit, sortOrder, dateRange, numToDisplay, normalize }) => {
monitorId,
limit,
sortOrder,
dateRange,
numToDisplay,
normalize,
}) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME); const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try { try {
// Get monitor, if we can't find it, abort with error // Get monitor, if we can't find it, abort with error
@@ -408,12 +381,7 @@ const getMonitorStatsById = async ({
// Get Checks for monitor in date range requested // Get Checks for monitor in date range requested
const model = CHECK_MODEL_LOOKUP[monitor.type]; const model = CHECK_MODEL_LOOKUP[monitor.type];
const dates = getDateRange(dateRange); const dates = getDateRange(dateRange);
const { checksAll, checksForDateRange } = await getMonitorChecks( const { checksAll, checksForDateRange } = await getMonitorChecks(monitorId, model, dates, sort);
monitorId,
model,
dates,
sort
);
// Build monitor stats // Build monitor stats
const monitorStats = { const monitorStats = {
@@ -423,20 +391,10 @@ const getMonitorStatsById = async ({
latestResponseTime: getLatestResponseTime(checksAll), latestResponseTime: getLatestResponseTime(checksAll),
periodIncidents: getIncidents(checksForDateRange), periodIncidents: getIncidents(checksForDateRange),
periodTotalChecks: checksForDateRange.length, periodTotalChecks: checksForDateRange.length,
checks: processChecksForDisplay( checks: processChecksForDisplay(NormalizeData, checksForDateRange, numToDisplay, normalize),
NormalizeData,
checksForDateRange,
numToDisplay,
normalize
),
}; };
if ( if (monitor.type === "http" || monitor.type === "ping" || monitor.type === "docker" || monitor.type === "port") {
monitor.type === "http" ||
monitor.type === "ping" ||
monitor.type === "docker" ||
monitor.type === "port"
) {
// HTTP/PING Specific stats // HTTP/PING Specific stats
monitorStats.periodAvgResponseTime = getAverageResponseTime(checksForDateRange); monitorStats.periodAvgResponseTime = getAverageResponseTime(checksForDateRange);
monitorStats.periodUptime = getUptimePercentage(checksForDateRange); monitorStats.periodUptime = getUptimePercentage(checksForDateRange);
@@ -463,9 +421,7 @@ const getHardwareDetailsById = async ({ monitorId, dateRange }) => {
month: "%Y-%m-%dT00:00:00Z", month: "%Y-%m-%dT00:00:00Z",
}; };
const dateString = formatLookup[dateRange]; const dateString = formatLookup[dateRange];
const hardwareStats = await HardwareCheck.aggregate( const hardwareStats = await HardwareCheck.aggregate(buildHardwareDetailsPipeline(monitor, dates, dateString));
buildHardwareDetailsPipeline(monitor, dates, dateString)
);
const monitorStats = { const monitorStats = {
...monitor.toObject(), ...monitor.toObject(),
@@ -505,16 +461,18 @@ const getMonitorById = async (monitorId) => {
} }
}; };
const getMonitorsByTeamId = async ({ const getMonitorsByIds = async (monitorIds) => {
limit, try {
type, const objectIds = monitorIds.map((id) => new ObjectId(id));
page, return await Monitor.find({ _id: { $in: objectIds } }, { _id: 1, teamId: 1 }).lean();
rowsPerPage, } catch (error) {
filter, error.service = SERVICE_NAME;
field, error.method = "getMonitorsByIds";
order, throw error;
teamId, }
}) => { };
const getMonitorsByTeamId = async ({ limit, type, page, rowsPerPage, filter, field, order, teamId }) => {
limit = parseInt(limit); limit = parseInt(limit);
page = parseInt(page); page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage); rowsPerPage = parseInt(rowsPerPage);
@@ -528,14 +486,10 @@ const getMonitorsByTeamId = async ({
matchStage.type = Array.isArray(type) ? { $in: type } : type; matchStage.type = Array.isArray(type) ? { $in: type } : type;
} }
const summaryResult = await Monitor.aggregate( const summaryResult = await Monitor.aggregate(buildMonitorSummaryByTeamIdPipeline({ matchStage }));
buildMonitorSummaryByTeamIdPipeline({ matchStage })
);
const summary = summaryResult[0]; const summary = summaryResult[0];
const monitors = await Monitor.aggregate( const monitors = await Monitor.aggregate(buildMonitorsByTeamIdPipeline({ matchStage, field, order }));
buildMonitorsByTeamIdPipeline({ matchStage, field, order })
);
const filteredMonitors = await Monitor.aggregate( const filteredMonitors = await Monitor.aggregate(
buildFilteredMonitorsByTeamIdPipeline({ buildFilteredMonitorsByTeamIdPipeline({
@@ -569,14 +523,10 @@ const getMonitorsAndSummaryByTeamId = async ({ type, explain, teamId }) => {
} }
if (explain === true) { if (explain === true) {
return Monitor.aggregate( return Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })).explain("executionStats");
buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })
).explain("executionStats");
} }
const queryResult = await Monitor.aggregate( const queryResult = await Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage }));
buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })
);
const { monitors, summary } = queryResult?.[0] ?? {}; const { monitors, summary } = queryResult?.[0] ?? {};
return { monitors, summary }; return { monitors, summary };
} catch (error) { } catch (error) {
@@ -586,17 +536,7 @@ const getMonitorsAndSummaryByTeamId = async ({ type, explain, teamId }) => {
} }
}; };
const getMonitorsWithChecksByTeamId = async ({ const getMonitorsWithChecksByTeamId = async ({ limit, type, page, rowsPerPage, filter, field, order, teamId, explain }) => {
limit,
type,
page,
rowsPerPage,
filter,
field,
order,
teamId,
explain,
}) => {
try { try {
limit = parseInt(limit); limit = parseInt(limit);
page = parseInt(page); page = parseInt(page);
@@ -684,9 +624,7 @@ const createMonitor = async ({ body, teamId, userId }) => {
*/ */
const createBulkMonitors = async (req) => { const createBulkMonitors = async (req) => {
try { try {
const monitors = req.map( const monitors = req.map((item) => new Monitor({ ...item, notifications: undefined }));
(item) => new Monitor({ ...item, notifications: undefined })
);
await Monitor.bulkSave(monitors); await Monitor.bulkSave(monitors);
return monitors; return monitors;
} catch (error) { } catch (error) {
@@ -826,6 +764,7 @@ export {
getAllMonitorsWithUptimeStats, getAllMonitorsWithUptimeStats,
getMonitorStatsById, getMonitorStatsById,
getMonitorById, getMonitorById,
getMonitorsByIds,
getMonitorsByTeamId, getMonitorsByTeamId,
getMonitorsAndSummaryByTeamId, getMonitorsAndSummaryByTeamId,
getMonitorsWithChecksByTeamId, getMonitorsWithChecksByTeamId,
+12 -64
View File
@@ -31,11 +31,7 @@ const buildUptimeDetailsPipeline = (monitorId, dates, dateString) => {
$project: { $project: {
_id: 0, _id: 0,
percentage: { percentage: {
$cond: [ $cond: [{ $eq: ["$totalChecks", 0] }, 0, { $divide: ["$upChecks", "$totalChecks"] }],
{ $eq: ["$totalChecks", 0] },
0,
{ $divide: ["$upChecks", "$totalChecks"] },
],
}, },
}, },
}, },
@@ -235,11 +231,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
{ {
$match: { $match: {
$expr: { $expr: {
$and: [ $and: [{ $eq: ["$monitorId", monitor._id] }, { $gte: ["$createdAt", dates.start] }, { $lte: ["$createdAt", dates.end] }],
{ $eq: ["$monitorId", monitor._id] },
{ $gte: ["$createdAt", dates.start] },
{ $lte: ["$createdAt", dates.end] },
],
}, },
}, },
}, },
@@ -326,10 +318,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
input: "$disks", input: "$disks",
as: "diskArray", as: "diskArray",
in: { in: {
$arrayElemAt: [ $arrayElemAt: ["$$diskArray.read_speed_bytes", "$$diskIndex"],
"$$diskArray.read_speed_bytes",
"$$diskIndex",
],
}, },
}, },
}, },
@@ -340,10 +329,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
input: "$disks", input: "$disks",
as: "diskArray", as: "diskArray",
in: { in: {
$arrayElemAt: [ $arrayElemAt: ["$$diskArray.write_speed_bytes", "$$diskIndex"],
"$$diskArray.write_speed_bytes",
"$$diskIndex",
],
}, },
}, },
}, },
@@ -354,10 +340,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
input: "$disks", input: "$disks",
as: "diskArray", as: "diskArray",
in: { in: {
$arrayElemAt: [ $arrayElemAt: ["$$diskArray.total_bytes", "$$diskIndex"],
"$$diskArray.total_bytes",
"$$diskIndex",
],
}, },
}, },
}, },
@@ -379,10 +362,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
input: "$disks", input: "$disks",
as: "diskArray", as: "diskArray",
in: { in: {
$arrayElemAt: [ $arrayElemAt: ["$$diskArray.usage_percent", "$$diskIndex"],
"$$diskArray.usage_percent",
"$$diskIndex",
],
}, },
}, },
}, },
@@ -556,26 +536,14 @@ const buildMonitorsAndSummaryByTeamIdPipeline = ({ matchStage }) => {
]; ];
}; };
const buildMonitorsWithChecksByTeamIdPipeline = ({ const buildMonitorsWithChecksByTeamIdPipeline = ({ matchStage, filter, page, rowsPerPage, field, order, limit, type }) => {
matchStage,
filter,
page,
rowsPerPage,
field,
order,
limit,
type,
}) => {
const skip = page && rowsPerPage ? page * rowsPerPage : 0; const skip = page && rowsPerPage ? page * rowsPerPage : 0;
const sort = { [field]: order === "asc" ? 1 : -1 }; const sort = { [field]: order === "asc" ? 1 : -1 };
const limitStage = rowsPerPage ? [{ $limit: rowsPerPage }] : []; const limitStage = rowsPerPage ? [{ $limit: rowsPerPage }] : [];
// Match name // Match name
if (typeof filter !== "undefined" && field === "name") { if (typeof filter !== "undefined" && field === "name") {
matchStage.$or = [ matchStage.$or = [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }];
{ name: { $regex: filter, $options: "i" } },
{ url: { $regex: filter, $options: "i" } },
];
} }
// Match isActive // Match isActive
@@ -667,37 +635,20 @@ const buildMonitorsWithChecksByTeamIdPipeline = ({
return pipeline; return pipeline;
}; };
const buildFilteredMonitorsByTeamIdPipeline = ({ const buildFilteredMonitorsByTeamIdPipeline = ({ matchStage, filter, page, rowsPerPage, field, order, limit, type }) => {
matchStage,
filter,
page,
rowsPerPage,
field,
order,
limit,
type,
}) => {
const skip = page && rowsPerPage ? page * rowsPerPage : 0; const skip = page && rowsPerPage ? page * rowsPerPage : 0;
const sort = { [field]: order === "asc" ? 1 : -1 }; const sort = { [field]: order === "asc" ? 1 : -1 };
const limitStage = rowsPerPage ? [{ $limit: rowsPerPage }] : []; const limitStage = rowsPerPage ? [{ $limit: rowsPerPage }] : [];
if (typeof filter !== "undefined" && field === "name") { if (typeof filter !== "undefined" && field === "name") {
matchStage.$or = [ matchStage.$or = [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }];
{ name: { $regex: filter, $options: "i" } },
{ url: { $regex: filter, $options: "i" } },
];
} }
if (typeof filter !== "undefined" && field === "status") { if (typeof filter !== "undefined" && field === "status") {
matchStage.status = filter === "true"; matchStage.status = filter === "true";
} }
const pipeline = [ const pipeline = [{ $match: matchStage }, { $sort: sort }, { $skip: skip }, ...limitStage];
{ $match: matchStage },
{ $sort: sort },
{ $skip: skip },
...limitStage,
];
// Add checks // Add checks
if (limit) { if (limit) {
@@ -792,10 +743,7 @@ const buildGetMonitorsByTeamIdPipeline = (req) => {
? [ ? [
{ {
$match: { $match: {
$or: [ $or: [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }],
{ name: { $regex: filter, $options: "i" } },
{ url: { $regex: filter, $options: "i" } },
],
}, },
}, },
] ]
@@ -32,9 +32,7 @@ const createNetworkCheck = async (networkCheckData) => {
*/ */
const getNetworkChecksByMonitorId = async (monitorId, limit = 100) => { const getNetworkChecksByMonitorId = async (monitorId, limit = 100) => {
try { try {
const networkChecks = await NetworkCheck.find({ monitorId }) const networkChecks = await NetworkCheck.find({ monitorId }).sort({ createdAt: -1 }).limit(limit);
.sort({ createdAt: -1 })
.limit(limit);
return networkChecks; return networkChecks;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
+1 -3
View File
@@ -29,9 +29,7 @@ const updateAppSettings = async (newSettings) => {
await AppSettings.findOneAndUpdate({}, update, { await AppSettings.findOneAndUpdate({}, update, {
upsert: true, upsert: true,
}); });
const settings = await AppSettings.findOne() const settings = await AppSettings.findOne().select("-__v -_id -createdAt -updatedAt -singleton").lean();
.select("-__v -_id -createdAt -updatedAt -singleton")
.lean();
return settings; return settings;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
+5 -20
View File
@@ -48,13 +48,9 @@ const updateStatusPage = async (statusPageData, image) => {
if (statusPageData.deleteSubmonitors === "true") { if (statusPageData.deleteSubmonitors === "true") {
statusPageData.subMonitors = []; statusPageData.subMonitors = [];
} }
const statusPage = await StatusPage.findOneAndUpdate( const statusPage = await StatusPage.findOneAndUpdate({ url: statusPageData.url }, statusPageData, {
{ url: statusPageData.url }, new: true,
statusPageData, });
{
new: true,
}
);
return statusPage; return statusPage;
} catch (error) { } catch (error) {
@@ -98,19 +94,8 @@ const getStatusPage = async (url) => {
} }
if (!preliminaryStatusPage.monitors || preliminaryStatusPage.monitors.length === 0) { if (!preliminaryStatusPage.monitors || preliminaryStatusPage.monitors.length === 0) {
const { const { _id, color, companyName, isPublished, logo, originalMonitors, showCharts, showUptimePercentage, timezone, showAdminLoginLink, url } =
_id, preliminaryStatusPage;
color,
companyName,
isPublished,
logo,
originalMonitors,
showCharts,
showUptimePercentage,
timezone,
showAdminLoginLink,
url,
} = preliminaryStatusPage;
return { return {
statusPage: { statusPage: {
_id, _id,
+16 -36
View File
@@ -16,11 +16,7 @@ const SERVICE_NAME = "userModule";
* @returns {Promise<UserModel>} * @returns {Promise<UserModel>}
* @throws {Error} * @throws {Error}
*/ */
const insertUser = async ( const insertUser = async (userData, imageFile, generateAvatarImage = GenerateAvatarImage) => {
userData,
imageFile,
generateAvatarImage = GenerateAvatarImage
) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME); const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try { try {
if (imageFile) { if (imageFile) {
@@ -47,9 +43,7 @@ const insertUser = async (
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("-profileImage"); // .select() doesn't work with create, need to save then find
.select("-password")
.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 = stringService.dbUserExists; error.message = stringService.dbUserExists;
@@ -98,31 +92,26 @@ const getUserByEmail = async (email) => {
* @throws {Error} * @throws {Error}
*/ */
const updateUser = async ( const updateUser = async ({ userId, user, file }) => {
req, if (!userId) {
res, throw new Error("No user in request");
parseBoolean = ParseBoolean, }
generateAvatarImage = GenerateAvatarImage
) => {
const candidateUserId = req.params.userId;
try {
const candidateUser = { ...req.body };
// ******************************************
// Handle profile image
// ******************************************
if (parseBoolean(candidateUser.deleteProfileImage) === true) { try {
const candidateUser = { ...user };
if (ParseBoolean(candidateUser.deleteProfileImage) === true) {
candidateUser.profileImage = null; candidateUser.profileImage = null;
candidateUser.avatarImage = null; candidateUser.avatarImage = null;
} else if (req.file) { } else if (file) {
// 1. Save the full size image // 1. Save the full size image
candidateUser.profileImage = { candidateUser.profileImage = {
data: req.file.buffer, data: file.buffer,
contentType: req.file.mimetype, contentType: file.mimetype,
}; };
// 2. Get the avatar sized image // 2. Get the avatar sized image
const avatar = await generateAvatarImage(req.file); const avatar = await GenerateAvatarImage(file);
candidateUser.avatarImage = avatar; candidateUser.avatarImage = avatar;
} }
@@ -131,7 +120,7 @@ const updateUser = async (
// ****************************************** // ******************************************
const updatedUser = await UserModel.findByIdAndUpdate( const updatedUser = await UserModel.findByIdAndUpdate(
candidateUserId, userId,
candidateUser, candidateUser,
{ new: true } // Returns updated user instead of pre-update user { new: true } // Returns updated user instead of pre-update user
) )
@@ -220,13 +209,4 @@ const logoutUser = async (userId) => {
} }
}; };
export { export { insertUser, getUserByEmail, updateUser, deleteUser, deleteTeam, deleteAllOtherUsers, getAllUsers, logoutUser };
insertUser,
getUserByEmail,
updateUser,
deleteUser,
deleteTeam,
deleteAllOtherUsers,
getAllUsers,
logoutUser,
};
+16 -44
View File
@@ -99,9 +99,7 @@ const SHUTDOWN_TIMEOUT = 1000;
let isShuttingDown = false; let isShuttingDown = false;
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); const __dirname = path.dirname(__filename);
const openApiSpec = JSON.parse( const openApiSpec = JSON.parse(fs.readFileSync(path.join(__dirname, "openapi.json"), "utf8"));
fs.readFileSync(path.join(__dirname, "openapi.json"), "utf8")
);
const frontendPath = path.join(__dirname, "public"); const frontendPath = path.join(__dirname, "public");
@@ -156,25 +154,8 @@ const startApp = async () => {
// Set allowed origin // Set allowed origin
const allowedOrigin = appSettings.clientHost; const allowedOrigin = appSettings.clientHost;
const networkService = new NetworkService( const networkService = new NetworkService(axios, ping, logger, http, Docker, net, stringService, settingsService);
axios, const emailService = new EmailService(settingsService, fs, path, compile, mjml2html, nodemailer, logger);
ping,
logger,
http,
Docker,
net,
stringService,
settingsService
);
const emailService = new EmailService(
settingsService,
fs,
path,
compile,
mjml2html,
nodemailer,
logger
);
const bufferService = new BufferService({ db, logger }); const bufferService = new BufferService({ db, logger });
const statusService = new StatusService({ db, logger, buffer: bufferService }); const statusService = new StatusService({ db, logger, buffer: bufferService });
const notificationUtils = new NotificationUtils({ const notificationUtils = new NotificationUtils({
@@ -292,17 +273,11 @@ const startApp = async () => {
ServiceRegistry.get(StringService.SERVICE_NAME) ServiceRegistry.get(StringService.SERVICE_NAME)
); );
const queueController = new QueueController( const queueController = new QueueController(ServiceRegistry.get(JobQueue.SERVICE_NAME), ServiceRegistry.get(StringService.SERVICE_NAME));
ServiceRegistry.get(JobQueue.SERVICE_NAME),
ServiceRegistry.get(StringService.SERVICE_NAME)
);
const logController = new LogController(logger); const logController = new LogController(logger);
const statusPageController = new StatusPageController( const statusPageController = new StatusPageController(ServiceRegistry.get(MongoDB.SERVICE_NAME), ServiceRegistry.get(StringService.SERVICE_NAME));
ServiceRegistry.get(MongoDB.SERVICE_NAME),
ServiceRegistry.get(StringService.SERVICE_NAME)
);
const notificationController = new NotificationController({ const notificationController = new NotificationController({
notificationService: ServiceRegistry.get(NotificationService.SERVICE_NAME), notificationService: ServiceRegistry.get(NotificationService.SERVICE_NAME),
@@ -311,9 +286,7 @@ const startApp = async () => {
db: ServiceRegistry.get(MongoDB.SERVICE_NAME), db: ServiceRegistry.get(MongoDB.SERVICE_NAME),
}); });
const diagnosticController = new DiagnosticController( const diagnosticController = new DiagnosticController(ServiceRegistry.get(MongoDB.SERVICE_NAME));
ServiceRegistry.get(MongoDB.SERVICE_NAME)
);
//Create routes //Create routes
const authRoutes = new AuthRoutes(authController); const authRoutes = new AuthRoutes(authController);
@@ -321,9 +294,7 @@ const startApp = async () => {
const settingsRoutes = new SettingsRoutes(settingsController); const settingsRoutes = new SettingsRoutes(settingsController);
const checkRoutes = new CheckRoutes(checkController); const checkRoutes = new CheckRoutes(checkController);
const inviteRoutes = new InviteRoutes(inviteController); const inviteRoutes = new InviteRoutes(inviteController);
const maintenanceWindowRoutes = new MaintenanceWindowRoutes( const maintenanceWindowRoutes = new MaintenanceWindowRoutes(maintenanceWindowController);
maintenanceWindowController
);
const queueRoutes = new QueueRoutes(queueController); const queueRoutes = new QueueRoutes(queueController);
const logRoutes = new LogRoutes(logController); const logRoutes = new LogRoutes(logController);
const statusPageRoutes = new StatusPageRoutes(statusPageController); const statusPageRoutes = new StatusPageRoutes(statusPageController);
@@ -372,16 +343,17 @@ const startApp = async () => {
//routes //routes
app.use("/api/v1/auth", authRoutes.getRouter()); app.use("/api/v1/auth", authRoutes.getRouter());
app.use("/api/v1/settings", verifyJWT, settingsRoutes.getRouter());
app.use("/api/v1/invite", inviteRoutes.getRouter());
app.use("/api/v1/monitors", verifyJWT, monitorRoutes.getRouter());
app.use("/api/v1/checks", verifyJWT, checkRoutes.getRouter()); app.use("/api/v1/checks", verifyJWT, checkRoutes.getRouter());
app.use("/api/v1/maintenance-window", verifyJWT, maintenanceWindowRoutes.getRouter());
app.use("/api/v1/queue", verifyJWT, queueRoutes.getRouter());
app.use("/api/v1/logs", verifyJWT, logRoutes.getRouter());
app.use("/api/v1/status-page", statusPageRoutes.getRouter());
app.use("/api/v1/notifications", verifyJWT, notificationRoutes.getRouter());
app.use("/api/v1/diagnostic", verifyJWT, diagnosticRoutes.getRouter()); app.use("/api/v1/diagnostic", verifyJWT, diagnosticRoutes.getRouter());
app.use("/api/v1/invite", inviteRoutes.getRouter());
app.use("/api/v1/logs", verifyJWT, logRoutes.getRouter());
app.use("/api/v1/maintenance-window", verifyJWT, maintenanceWindowRoutes.getRouter());
app.use("/api/v1/monitors", verifyJWT, monitorRoutes.getRouter());
app.use("/api/v1/notifications", verifyJWT, notificationRoutes.getRouter());
app.use("/api/v1/queue", verifyJWT, queueRoutes.getRouter());
app.use("/api/v1/settings", verifyJWT, settingsRoutes.getRouter());
app.use("/api/v1/status-page", statusPageRoutes.getRouter());
app.use("/api/v1/health", (req, res) => { app.use("/api/v1/health", (req, res) => {
res.json({ res.json({
status: "OK", status: "OK",
+1 -3
View File
@@ -29,9 +29,7 @@ const isAllowed = (allowedRoles) => {
// 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 } = ServiceRegistry.get( const { jwtSecret } = ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings();
SettingsService.SERVICE_NAME
).getSettings();
var decoded = jwt.verify(parsedToken, jwtSecret); var decoded = jwt.verify(parsedToken, jwtSecret);
const userRoles = decoded.role; const userRoles = decoded.role;
+19 -20
View File
@@ -1,28 +1,27 @@
import logger from "../utils/logger.js"; import logger from "../utils/logger.js";
const languageMiddleware = const languageMiddleware = (stringService, translationService) => async (req, res, next) => {
(stringService, translationService) => async (req, res, next) => { try {
try { const acceptLanguage = req.headers["accept-language"] || "en";
const acceptLanguage = req.headers["accept-language"] || "en"; const language = acceptLanguage.split(",")[0].slice(0, 2).toLowerCase();
const language = acceptLanguage.split(",")[0].slice(0, 2).toLowerCase();
translationService.setLanguage(language); translationService.setLanguage(language);
stringService.setLanguage(language); stringService.setLanguage(language);
next(); next();
} catch (error) { } catch (error) {
logger.error({ logger.error({
message: error.message, message: error.message,
service: "languageMiddleware", service: "languageMiddleware",
}); });
const acceptLanguage = req.headers["accept-language"] || "en"; const acceptLanguage = req.headers["accept-language"] || "en";
const language = acceptLanguage.split(",")[0].slice(0, 2).toLowerCase(); const language = acceptLanguage.split(",")[0].slice(0, 2).toLowerCase();
translationService.setLanguage(language); translationService.setLanguage(language);
stringService.setLanguage(language); stringService.setLanguage(language);
next(); next();
} }
}; };
export default languageMiddleware; export default languageMiddleware;
+7 -7
View File
@@ -39,13 +39,13 @@ const verifyJWT = (req, res, next) => {
const { jwtSecret } = ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings(); const { jwtSecret } = ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings();
jwt.verify(parsedToken, jwtSecret, (err, decoded) => { jwt.verify(parsedToken, jwtSecret, (err, decoded) => {
if (err) { if (err) {
if (err) { const errorMessage = err.name === "TokenExpiredError" ? stringService.expiredAuthToken : stringService.invalidAuthToken;
const errorMessage = err.details = { msg: errorMessage };
err.name === "TokenExpiredError" err.status = 401;
? stringService.expiredAuthToken err.service = SERVICE_NAME;
: stringService.invalidAuthToken; err.method = "verifyJWT";
return res.status(401).json({ success: false, msg: errorMessage }); next(err);
} return;
} else { } else {
// Token is valid, carry on // Token is valid, carry on
req.user = decoded; req.user = decoded;
+1 -3
View File
@@ -47,9 +47,7 @@ const verifySuperAdmin = (req, res, next) => {
stack: err.stack, stack: err.stack,
details: stringService.invalidAuthToken, details: stringService.invalidAuthToken,
}); });
return res return res.status(401).json({ success: false, msg: stringService.invalidAuthToken });
.status(401)
.json({ success: false, msg: stringService.invalidAuthToken });
} }
if (decoded.role.includes("superadmin") === false) { if (decoded.role.includes("superadmin") === false) {
+1 -8
View File
@@ -100,14 +100,7 @@
"application/json": { "application/json": {
"schema": { "schema": {
"type": "object", "type": "object",
"required": [ "required": ["firstName", "lastName", "email", "password", "role", "teamId"],
"firstName",
"lastName",
"email",
"password",
"role",
"teamId"
],
"properties": { "properties": {
"firstName": { "firstName": {
"type": "string" "type": "string"
+1 -6
View File
@@ -15,12 +15,7 @@ class AnnouncementRoutes {
* @desc Create a new announcement * @desc Create a new announcement
* @access Private (Requires JWT verification) * @access Private (Requires JWT verification)
*/ */
this.router.post( this.router.post("/", verifyJWT, isAllowed(["admin", "superadmin"]), this.announcementController.createAnnouncement);
"/",
verifyJWT,
isAllowed(["admin", "superadmin"]),
this.announcementController.createAnnouncement
);
/** /**
* @route GET / * @route GET /
+8 -29
View File
@@ -15,40 +15,19 @@ class AuthRoutes {
} }
initRoutes() { initRoutes() {
this.router.post( this.router.post("/register", upload.single("profileImage"), this.authController.registerUser);
"/register",
upload.single("profileImage"),
this.authController.registerUser
);
this.router.post("/login", this.authController.loginUser); this.router.post("/login", this.authController.loginUser);
this.router.put(
"/user/:userId",
upload.single("profileImage"),
verifyJWT,
this.authController.editUser
);
this.router.get("/users/superadmin", this.authController.checkSuperadminExists);
this.router.get(
"/users",
verifyJWT,
isAllowed(["admin", "superadmin"]),
this.authController.getAllUsers
);
this.router.delete(
"/user/:userId",
verifyJWT,
verifyOwnership(User, "userId"),
this.authController.deleteUser
);
// Recovery routes
this.router.post("/recovery/request", this.authController.requestRecovery); this.router.post("/recovery/request", this.authController.requestRecovery);
this.router.post("/recovery/validate", this.authController.validateRecovery); this.router.post("/recovery/validate", this.authController.validateRecovery);
this.router.post("/recovery/reset/", this.authController.resetPassword); this.router.post("/recovery/reset/", this.authController.resetPassword);
this.router.get("/users/superadmin", this.authController.checkSuperadminExists);
this.router.get("/users", verifyJWT, isAllowed(["admin", "superadmin"]), this.authController.getAllUsers);
this.router.put("/user", verifyJWT, upload.single("profileImage"), this.authController.editUser);
this.router.delete("/user", verifyJWT, this.authController.deleteUser);
} }
getRouter() { getRouter() {
+7 -26
View File
@@ -13,35 +13,16 @@ class CheckRoutes {
} }
initRoutes() { initRoutes() {
this.router.get("/team", this.checkController.getChecksByTeam);
this.router.get("/team/summary", this.checkController.getChecksSummaryByTeamId); this.router.get("/team/summary", this.checkController.getChecksSummaryByTeamId);
this.router.delete( this.router.get("/team", this.checkController.getChecksByTeam);
"/team", this.router.put("/team/ttl", isAllowed(["admin", "superadmin"]), this.checkController.updateChecksTTL);
isAllowed(["admin", "superadmin"]), this.router.delete("/team", isAllowed(["admin", "superadmin"]), this.checkController.deleteChecksByTeamId);
this.checkController.deleteChecksByTeamId
); this.router.put("/check/:checkId", this.checkController.ackCheck);
this.router.put(
"/check/:checkId",
verifyTeamAccess(Check, "checkId"),
this.checkController.ackCheck
);
this.router.put(
"/team/ttl",
isAllowed(["admin", "superadmin"]),
this.checkController.updateChecksTTL
);
this.router.get("/:monitorId", this.checkController.getChecksByMonitor); this.router.get("/:monitorId", this.checkController.getChecksByMonitor);
this.router.post( this.router.delete("/:monitorId", this.checkController.deleteChecks);
"/:monitorId",
verifyOwnership(Monitor, "monitorId"),
this.checkController.createCheck
);
this.router.delete(
"/:monitorId",
verifyOwnership(Monitor, "monitorId"),
this.checkController.deleteChecks
);
this.router.put("/:path/:monitorId?", this.checkController.ackAllChecks); this.router.put("/:path/:monitorId?", this.checkController.ackAllChecks);
} }
+3 -7
View File
@@ -1,4 +1,6 @@
import { Router } from "express"; import { Router } from "express";
import { verifyJWT } from "../middleware/verifyJWT.js";
import { isAllowed } from "../middleware/isAllowed.js";
class DiagnosticRoutes { class DiagnosticRoutes {
constructor(diagnosticController) { constructor(diagnosticController) {
@@ -7,13 +9,7 @@ class DiagnosticRoutes {
this.initRoutes(); this.initRoutes();
} }
initRoutes() { initRoutes() {
this.router.get( this.router.get("/system", verifyJWT, isAllowed(["admin", "superadmin"]), this.diagnosticController.getSystemStats);
"/db/get-monitors-by-team-id/:teamId",
this.diagnosticController.getMonitorsByTeamIdExecutionStats
);
this.router.post("/db/stats", this.diagnosticController.getDbStats);
this.router.get("/system", this.diagnosticController.getSystemStats);
} }
getRouter() { getRouter() {
+1 -7
View File
@@ -10,15 +10,9 @@ class InviteRoutes {
} }
initRoutes() { initRoutes() {
this.router.post(
"/",
isAllowed(["admin", "superadmin"]),
verifyJWT,
this.inviteController.getInviteToken
);
this.router.post("/send", this.inviteController.sendInviteEmail); this.router.post("/send", this.inviteController.sendInviteEmail);
this.router.post("/verify", this.inviteController.inviteVerifyController); this.router.post("/verify", this.inviteController.inviteVerifyController);
this.router.post("/", verifyJWT, isAllowed(["admin", "superadmin"]), this.inviteController.getInviteToken);
} }
getRouter() { getRouter() {
+7 -28
View File
@@ -1,41 +1,20 @@
import { Router } from "express"; import { Router } from "express";
import { verifyOwnership } from "../middleware/verifyOwnership.js";
import { verifyTeamAccess } from "../middleware/verifyTeamAccess.js";
import Monitor from "../db/models/Monitor.js";
import MaintenanceWindow from "../db/models/MaintenanceWindow.js"; import MaintenanceWindow from "../db/models/MaintenanceWindow.js";
class MaintenanceWindowRoutes { class MaintenanceWindowRoutes {
constructor(maintenanceWindowController) { constructor(maintenanceWindowController) {
this.router = Router(); this.router = Router();
this.maintenanceWindowController = maintenanceWindowController; this.mwController = maintenanceWindowController;
this.initRoutes(); this.initRoutes();
} }
initRoutes() { initRoutes() {
this.router.post("/", this.maintenanceWindowController.createMaintenanceWindows); this.router.post("/", this.mwController.createMaintenanceWindows);
this.router.get("/team/", this.mwController.getMaintenanceWindowsByTeamId);
this.router.get( this.router.get("/monitor/:monitorId", this.mwController.getMaintenanceWindowsByMonitorId);
"/monitor/:monitorId",
verifyOwnership(Monitor, "monitorId"),
this.maintenanceWindowController.getMaintenanceWindowsByMonitorId
);
this.router.get( this.router.get("/:id", this.mwController.getMaintenanceWindowById);
"/team/", this.router.put("/:id", this.mwController.editMaintenanceWindow);
this.maintenanceWindowController.getMaintenanceWindowsByTeamId this.router.delete("/:id", this.mwController.deleteMaintenanceWindow);
);
this.router.get("/:id", this.maintenanceWindowController.getMaintenanceWindowById);
this.router.put(
"/:id",
verifyTeamAccess(MaintenanceWindow, "id"),
this.maintenanceWindowController.editMaintenanceWindow
);
this.router.delete(
"/:id",
verifyTeamAccess(MaintenanceWindow, "id"),
this.maintenanceWindowController.deleteMaintenanceWindow
);
} }
getRouter() { getRouter() {
+34 -88
View File
@@ -17,103 +17,49 @@ class MonitorRoutes {
} }
initRoutes() { initRoutes() {
this.router.get("/", this.monitorController.getAllMonitors); // Team routes
this.router.get("/uptime", this.monitorController.getAllMonitorsWithUptimeStats);
this.router.get(
"/export",
isAllowed(["admin", "superadmin"]),
this.monitorController.exportMonitorsToCSV
);
this.router.get("/stats/:monitorId", this.monitorController.getMonitorStatsById);
this.router.get(
"/hardware/details/:monitorId",
this.monitorController.getHardwareDetailsById
);
this.router.get(
"/uptime/details/:monitorId",
this.monitorController.getUptimeDetailsById
);
this.router.get("/certificate/:monitorId", (req, res, next) => {
this.monitorController.getMonitorCertificate(
req,
res,
next,
fetchMonitorCertificate
);
});
this.router.get("/team", this.monitorController.getMonitorsByTeamId); this.router.get("/team", this.monitorController.getMonitorsByTeamId);
this.router.get("/team/with-checks", this.monitorController.getMonitorsWithChecksByTeamId);
this.router.get("/summary/team", this.monitorController.getMonitorsAndSummaryByTeamId); // TODO should be /team/summary
// Uptime routes
this.router.get("/uptime", this.monitorController.getAllMonitorsWithUptimeStats);
this.router.get("/uptime/details/:monitorId", this.monitorController.getUptimeDetailsById);
// Hardware routes
this.router.get("/hardware/details/:monitorId", this.monitorController.getHardwareDetailsById);
// General monitor routes
this.router.post("/pause/:monitorId", isAllowed(["admin", "superadmin"]), this.monitorController.pauseMonitor);
this.router.get("/stats/:monitorId", this.monitorController.getMonitorStatsById);
// Util routes
this.router.get("/resolution/url", isAllowed(["admin", "superadmin"]), this.monitorController.checkEndpointResolution);
this.router.get("/certificate/:monitorId", (req, res, next) => {
this.monitorController.getMonitorCertificate(req, res, next, fetchMonitorCertificate);
});
// General monitor CRUD routes
this.router.get("/", this.monitorController.getAllMonitors);
this.router.post("/", isAllowed(["admin", "superadmin"]), this.monitorController.createMonitor);
this.router.delete("/", isAllowed(["superadmin"]), this.monitorController.deleteAllMonitors);
// Other static routes
this.router.post("/demo", isAllowed(["admin", "superadmin"]), this.monitorController.addDemoMonitors);
this.router.get("/export", isAllowed(["admin", "superadmin"]), this.monitorController.exportMonitorsToCSV);
this.router.post("/seed", isAllowed(["superadmin"]), this.monitorController.seedDb);
this.router.post("/bulk", isAllowed(["admin", "superadmin"]), upload.single("csvFile"), this.monitorController.createBulkMonitors);
this.router.post("/test-email", isAllowed(["admin", "superadmin"]), this.monitorController.sendTestEmail);
// Individual monitor CRUD routes
this.router.get("/:monitorId", this.monitorController.getMonitorById); this.router.get("/:monitorId", this.monitorController.getMonitorById);
this.router.put("/:monitorId", verifyTeamAccess(Monitor, "monitorId"), isAllowed(["admin", "superadmin"]), this.monitorController.editMonitor);
this.router.get(
"/summary/team",
this.monitorController.getMonitorsAndSummaryByTeamId
);
this.router.get(
"/team/with-checks",
this.monitorController.getMonitorsWithChecksByTeamId
);
this.router.get(
"/resolution/url",
isAllowed(["admin", "superadmin"]),
this.monitorController.checkEndpointResolution
);
this.router.delete( this.router.delete(
"/:monitorId", "/:monitorId",
verifyOwnership(Monitor, "monitorId"), verifyOwnership(Monitor, "monitorId"),
isAllowed(["admin", "superadmin"]), isAllowed(["admin", "superadmin"]),
this.monitorController.deleteMonitor this.monitorController.deleteMonitor
); );
this.router.post(
"/",
isAllowed(["admin", "superadmin"]),
this.monitorController.createMonitor
);
this.router.put(
"/:monitorId",
verifyTeamAccess(Monitor, "monitorId"),
isAllowed(["admin", "superadmin"]),
this.monitorController.editMonitor
);
this.router.delete(
"/",
isAllowed(["superadmin"]),
this.monitorController.deleteAllMonitors
);
this.router.post(
"/pause/:monitorId",
isAllowed(["admin", "superadmin"]),
this.monitorController.pauseMonitor
);
this.router.post(
"/demo",
isAllowed(["admin", "superadmin"]),
this.monitorController.addDemoMonitors
);
this.router.post(
"/bulk",
isAllowed(["admin", "superadmin"]),
upload.single("csvFile"),
this.monitorController.createBulkMonitors
);
this.router.post("/seed", isAllowed(["superadmin"]), this.monitorController.seedDb);
this.router.post(
"/test-email",
isAllowed(["admin", "superadmin"]),
this.monitorController.sendTestEmail
);
} }
getRouter() { getRouter() {
+5 -14
View File
@@ -13,25 +13,16 @@ class NotificationRoutes {
initializeRoutes() { initializeRoutes() {
this.router.use(verifyJWT); this.router.use(verifyJWT);
this.router.post("/test", this.notificationController.testNotification);
this.router.post("/test/all", this.notificationController.testAllNotifications);
this.router.post("/", this.notificationController.createNotification); this.router.post("/", this.notificationController.createNotification);
this.router.post("/test/all", this.notificationController.testAllNotifications);
this.router.post("/test", this.notificationController.testNotification);
this.router.get("/team", this.notificationController.getNotificationsByTeamId); this.router.get("/team", this.notificationController.getNotificationsByTeamId);
this.router.delete( this.router.delete("/:id", verifyOwnership(Notification, "id"), this.notificationController.deleteNotification);
"/:id",
verifyOwnership(Notification, "id"),
this.notificationController.deleteNotification
);
this.router.get("/:id", this.notificationController.getNotificationById); this.router.get("/:id", this.notificationController.getNotificationById);
this.router.put( this.router.put("/:id", verifyTeamAccess(Notification, "id"), this.notificationController.editNotification);
"/:id",
verifyTeamAccess(Notification, "id"),
this.notificationController.editNotification
);
} }
getRouter() { getRouter() {
+6 -34
View File
@@ -7,41 +7,13 @@ class QueueRoutes {
this.initRoutes(); this.initRoutes();
} }
initRoutes() { initRoutes() {
this.router.get( this.router.get("/jobs", isAllowed(["admin", "superadmin"]), this.queueController.getJobs);
"/metrics", this.router.post("/jobs", isAllowed(["admin", "superadmin"]), this.queueController.addJob);
isAllowed(["admin", "superadmin"]),
this.queueController.getMetrics
);
this.router.get( this.router.get("/metrics", isAllowed(["admin", "superadmin"]), this.queueController.getMetrics);
"/jobs", this.router.get("/health", isAllowed(["admin", "superadmin"]), this.queueController.checkQueueHealth);
isAllowed(["admin", "superadmin"]), this.router.get("/all-metrics", isAllowed(["admin", "superadmin"]), this.queueController.getAllMetrics);
this.queueController.getJobs this.router.post("/flush", isAllowed(["admin", "superadmin"]), this.queueController.flushQueue);
);
this.router.get(
"/all-metrics",
isAllowed(["admin", "superadmin"]),
this.queueController.getAllMetrics
);
this.router.post(
"/jobs",
isAllowed(["admin", "superadmin"]),
this.queueController.addJob
);
this.router.post(
"/flush",
isAllowed(["admin", "superadmin"]),
this.queueController.flushQueue
);
this.router.get(
"/health",
isAllowed(["admin", "superadmin"]),
this.queueController.checkQueueHealth
);
} }
getRouter() { getRouter() {
+2 -10
View File
@@ -10,16 +10,8 @@ class SettingsRoutes {
initRoutes() { initRoutes() {
this.router.get("/", this.settingsController.getAppSettings); this.router.get("/", this.settingsController.getAppSettings);
this.router.put( this.router.put("/", isAllowed(["admin", "superadmin"]), this.settingsController.updateAppSettings);
"/", this.router.post("/test-email", isAllowed(["admin", "superadmin"]), this.settingsController.sendTestEmail);
isAllowed(["admin", "superadmin"]),
this.settingsController.updateAppSettings
);
this.router.post(
"/test-email",
isAllowed(["admin", "superadmin"]),
this.settingsController.sendTestEmail
);
} }
getRouter() { getRouter() {
+4 -13
View File
@@ -13,20 +13,11 @@ class StatusPageRoutes {
initRoutes() { initRoutes() {
this.router.get("/", this.statusPageController.getStatusPage); this.router.get("/", this.statusPageController.getStatusPage);
this.router.get("/team", verifyJWT, this.statusPageController.getStatusPagesByTeamId); this.router.get("/team", verifyJWT, this.statusPageController.getStatusPagesByTeamId);
this.router.get("/:url", this.statusPageController.getStatusPageByUrl);
this.router.post( this.router.post("/", upload.single("logo"), verifyJWT, this.statusPageController.createStatusPage);
"/", this.router.put("/", upload.single("logo"), verifyJWT, this.statusPageController.updateStatusPage);
upload.single("logo"),
verifyJWT, this.router.get("/:url", this.statusPageController.getStatusPageByUrl);
this.statusPageController.createStatusPage
);
this.router.put(
"/",
upload.single("logo"),
verifyJWT,
this.statusPageController.updateStatusPage
);
this.router.delete("/:url(*)", verifyJWT, this.statusPageController.deleteStatusPage); this.router.delete("/:url(*)", verifyJWT, this.statusPageController.deleteStatusPage);
} }
+1 -5
View File
@@ -150,11 +150,7 @@ class JobQueue {
}; };
const schedulerId = getSchedulerId(monitor); const schedulerId = getSchedulerId(monitor);
await queue.upsertJobScheduler( await queue.upsertJobScheduler(schedulerId, { every: monitor?.interval ?? 60000 }, jobTemplate);
schedulerId,
{ every: monitor?.interval ?? 60000 },
jobTemplate
);
} }
async deleteJob(monitor) { async deleteJob(monitor) {
+2 -15
View File
@@ -1,16 +1,7 @@
const SERVICE_NAME = "JobQueueHelper"; const SERVICE_NAME = "JobQueueHelper";
class JobQueueHelper { class JobQueueHelper {
constructor({ constructor({ redisService, Queue, Worker, logger, db, networkService, statusService, notificationService }) {
redisService,
Queue,
Worker,
logger,
db,
networkService,
statusService,
notificationService,
}) {
this.db = db; this.db = db;
this.redisService = redisService; this.redisService = redisService;
this.Queue = Queue; this.Queue = Queue;
@@ -265,11 +256,7 @@ class JobQueueHelper {
// Handle status change // Handle status change
await job.updateProgress(60); await job.updateProgress(60);
const { const { monitor: updatedMonitor, statusChanged, prevStatus } = await this.statusService.updateStatus(networkResponse);
monitor: updatedMonitor,
statusChanged,
prevStatus,
} = await this.statusService.updateStatus(networkResponse);
// Handle notifications // Handle notifications
await job.updateProgress(80); await job.updateProgress(80);
this.notificationService this.notificationService
+2 -5
View File
@@ -22,8 +22,7 @@ class PulseQueue {
// **************************************** // ****************************************
init = async () => { init = async () => {
try { try {
const mongoConnectionString = const mongoConnectionString = this.appSettings.dbConnectionString || "mongodb://localhost:27017/uptime_db";
this.appSettings.dbConnectionString || "mongodb://localhost:27017/uptime_db";
this.pulse = new Pulse({ db: { address: mongoConnectionString } }); this.pulse = new Pulse({ db: { address: mongoConnectionString } });
await this.pulse.start(); await this.pulse.start();
this.pulse.define("monitor-job", this.pulseQueueHelper.getMonitorJob(), {}); this.pulse.define("monitor-job", this.pulseQueueHelper.getMonitorJob(), {});
@@ -186,9 +185,7 @@ class PulseQueue {
failReason: job.attrs.failReason, failReason: job.attrs.failReason,
lastRunAt: job.attrs.lastRunAt, lastRunAt: job.attrs.lastRunAt,
lastFinishedAt: job.attrs.lastFinishedAt, lastFinishedAt: job.attrs.lastFinishedAt,
lastRunTook: job.attrs.lockedAt lastRunTook: job.attrs.lockedAt ? null : job.attrs.lastFinishedAt - job.attrs.lastRunAt,
? null
: job.attrs.lastFinishedAt - job.attrs.lastRunAt,
lastFailedAt: job.attrs.failedAt, lastFailedAt: job.attrs.failedAt,
}; };
}); });
@@ -34,11 +34,7 @@ class PulseQueueHelper {
throw new Error("No network response"); throw new Error("No network response");
} }
const { const { monitor: updatedMonitor, statusChanged, prevStatus } = await this.statusService.updateStatus(networkResponse);
monitor: updatedMonitor,
statusChanged,
prevStatus,
} = await this.statusService.updateStatus(networkResponse);
this.notificationService this.notificationService
.handleNotifications({ .handleNotifications({
+1 -4
View File
@@ -42,10 +42,7 @@ class EmailService {
*/ */
this.loadTemplate = (templateName) => { this.loadTemplate = (templateName) => {
try { try {
const templatePath = this.path.join( const templatePath = this.path.join(__dirname, `../templates/${templateName}.mjml`);
__dirname,
`../templates/${templateName}.mjml`
);
const templateContent = this.fs.readFileSync(templatePath, "utf8"); const templateContent = this.fs.readFileSync(templatePath, "utf8");
return this.compile(templateContent); return this.compile(templateContent);
} catch (error) { } catch (error) {
+7 -28
View File
@@ -78,9 +78,7 @@ class NetworkService {
async requestPing(monitor) { async requestPing(monitor) {
try { try {
const url = monitor.url; const url = monitor.url;
const { response, responseTime, error } = await this.timeRequest(() => const { response, responseTime, error } = await this.timeRequest(() => this.ping.promise.probe(url));
this.ping.promise.probe(url)
);
const pingResponse = { const pingResponse = {
monitorId: monitor._id, monitorId: monitor._id,
@@ -133,18 +131,7 @@ class NetworkService {
*/ */
async requestHttp(monitor) { async requestHttp(monitor) {
try { try {
const { const { url, secret, _id, name, teamId, type, ignoreTlsErrors, jsonPath, matchMethod, expectedValue } = monitor;
url,
secret,
_id,
name,
teamId,
type,
ignoreTlsErrors,
jsonPath,
matchMethod,
expectedValue,
} = monitor;
const config = {}; const config = {};
secret !== undefined && (config.headers = { Authorization: `Bearer ${secret}` }); secret !== undefined && (config.headers = { Authorization: `Bearer ${secret}` });
@@ -155,9 +142,7 @@ class NetworkService {
}); });
} }
const { response, responseTime, error } = await this.timeRequest(() => const { response, responseTime, error } = await this.timeRequest(() => this.axios.get(url, config));
this.axios.get(url, config)
);
const httpResponse = { const httpResponse = {
monitorId: _id, monitorId: _id,
@@ -171,8 +156,7 @@ class NetworkService {
const code = error.response?.status || this.NETWORK_ERROR; const code = error.response?.status || this.NETWORK_ERROR;
httpResponse.code = code; httpResponse.code = code;
httpResponse.status = false; httpResponse.status = false;
httpResponse.message = httpResponse.message = this.http.STATUS_CODES[code] || this.stringService.httpNetworkError;
this.http.STATUS_CODES[code] || this.stringService.httpNetworkError;
return httpResponse; return httpResponse;
} }
@@ -227,9 +211,7 @@ class NetworkService {
else match = result === expectedValue; else match = result === expectedValue;
httpResponse.status = match; httpResponse.status = match;
httpResponse.message = match httpResponse.message = match ? this.stringService.httpMatchSuccess : this.stringService.httpMatchFail;
? this.stringService.httpMatchSuccess
: this.stringService.httpMatchFail;
return httpResponse; return httpResponse;
} catch (error) { } catch (error) {
error.service = this.SERVICE_NAME; error.service = this.SERVICE_NAME;
@@ -320,9 +302,7 @@ class NetworkService {
} }
const container = docker.getContainer(monitor.url); const container = docker.getContainer(monitor.url);
const { response, responseTime, error } = await this.timeRequest(() => const { response, responseTime, error } = await this.timeRequest(() => container.inspect());
container.inspect()
);
const dockerResponse = { const dockerResponse = {
monitorId: monitor._id, monitorId: monitor._id,
@@ -333,8 +313,7 @@ class NetworkService {
if (error) { if (error) {
dockerResponse.status = false; dockerResponse.status = false;
dockerResponse.code = error.statusCode || this.NETWORK_ERROR; dockerResponse.code = error.statusCode || this.NETWORK_ERROR;
dockerResponse.message = dockerResponse.message = error.reason || "Failed to fetch Docker container information";
error.reason || "Failed to fetch Docker container information";
return dockerResponse; return dockerResponse;
} }
dockerResponse.status = response?.State?.Status === "running" ? true : false; dockerResponse.status = response?.State?.Status === "running" ? true : false;
+4 -16
View File
@@ -3,14 +3,7 @@ const SERVICE_NAME = "NotificationService";
class NotificationService { class NotificationService {
static SERVICE_NAME = SERVICE_NAME; static SERVICE_NAME = SERVICE_NAME;
constructor({ constructor({ emailService, db, logger, networkService, stringService, notificationUtils }) {
emailService,
db,
logger,
networkService,
stringService,
notificationUtils,
}) {
this.emailService = emailService; this.emailService = emailService;
this.db = db; this.db = db;
this.logger = logger; this.logger = logger;
@@ -69,20 +62,15 @@ class NotificationService {
const alerts = await this.notificationUtils.buildHardwareAlerts(networkResponse); const alerts = await this.notificationUtils.buildHardwareAlerts(networkResponse);
if (alerts.length === 0) return false; if (alerts.length === 0) return false;
const { subject, html } = await this.notificationUtils.buildHardwareEmail( const { subject, html } = await this.notificationUtils.buildHardwareEmail(networkResponse, alerts);
networkResponse, const content = await this.notificationUtils.buildHardwareNotificationMessage(alerts);
alerts
);
const content =
await this.notificationUtils.buildHardwareNotificationMessage(alerts);
const success = await this.notifyAll({ notificationIDs, subject, html, content }); const success = await this.notifyAll({ notificationIDs, subject, html, content });
return success; return success;
} }
// Status monitors // Status monitors
const { subject, html } = const { subject, html } = await this.notificationUtils.buildStatusEmail(networkResponse);
await this.notificationUtils.buildStatusEmail(networkResponse);
const content = await this.notificationUtils.buildWebhookMessage(networkResponse); const content = await this.notificationUtils.buildWebhookMessage(networkResponse);
const success = this.notifyAll({ notificationIDs, subject, html, content }); const success = this.notifyAll({ notificationIDs, subject, html, content });
return success; return success;
+7 -29
View File
@@ -26,10 +26,7 @@ class NotificationUtils {
const date = new Date(timestamp); const date = new Date(timestamp);
// Get timezone abbreviation and format the date // Get timezone abbreviation and format the date
const timeZoneAbbr = date const timeZoneAbbr = date.toLocaleTimeString("en-US", { timeZoneName: "short" }).split(" ").pop();
.toLocaleTimeString("en-US", { timeZoneName: "short" })
.split(" ")
.pop();
// Format the date with readable format // Format the date with readable format
return ( return (
@@ -50,9 +47,7 @@ class NotificationUtils {
}; };
// Get formatted time // Get formatted time
const formattedTime = timestamp const formattedTime = timestamp ? formatTime(timestamp) : formatTime(new Date().getTime());
? formatTime(timestamp)
: formatTime(new Date().getTime());
// Create different messages based on status with extra spacing // Create different messages based on status with extra spacing
let messageText; let messageText;
@@ -73,29 +68,15 @@ class NotificationUtils {
buildHardwareAlerts = async (networkResponse) => { buildHardwareAlerts = async (networkResponse) => {
const monitor = networkResponse?.monitor; const monitor = networkResponse?.monitor;
const thresholds = networkResponse?.monitor?.thresholds; const thresholds = networkResponse?.monitor?.thresholds;
const { const { usage_cpu: cpuThreshold = -1, usage_memory: memoryThreshold = -1, usage_disk: diskThreshold = -1 } = thresholds;
usage_cpu: cpuThreshold = -1,
usage_memory: memoryThreshold = -1,
usage_disk: diskThreshold = -1,
} = thresholds;
const metrics = networkResponse?.payload?.data; const metrics = networkResponse?.payload?.data;
const { const { cpu: { usage_percent: cpuUsage = -1 } = {}, memory: { usage_percent: memoryUsage = -1 } = {}, disk = [] } = metrics;
cpu: { usage_percent: cpuUsage = -1 } = {},
memory: { usage_percent: memoryUsage = -1 } = {},
disk = [],
} = metrics;
const alerts = { const alerts = {
cpu: cpuThreshold !== -1 && cpuUsage > cpuThreshold ? true : false, cpu: cpuThreshold !== -1 && cpuUsage > cpuThreshold ? true : false,
memory: memoryThreshold !== -1 && memoryUsage > memoryThreshold ? true : false, memory: memoryThreshold !== -1 && memoryUsage > memoryThreshold ? true : false,
disk: disk: disk?.some((d) => diskThreshold !== -1 && typeof d?.usage_percent === "number" && d?.usage_percent > diskThreshold) ?? false,
disk?.some(
(d) =>
diskThreshold !== -1 &&
typeof d?.usage_percent === "number" &&
d?.usage_percent > diskThreshold
) ?? false,
}; };
const alertsToSend = []; const alertsToSend = [];
@@ -110,16 +91,13 @@ class NotificationUtils {
monitor[`${type}AlertThreshold`] = monitor.alertThreshold; monitor[`${type}AlertThreshold`] = monitor.alertThreshold;
const formatAlert = { const formatAlert = {
cpu: () => cpu: () => `Your current CPU usage (${(cpuUsage * 100).toFixed(0)}%) is above your threshold (${(cpuThreshold * 100).toFixed(0)}%)`,
`Your current CPU usage (${(cpuUsage * 100).toFixed(0)}%) is above your threshold (${(cpuThreshold * 100).toFixed(0)}%)`,
memory: () => memory: () =>
`Your current memory usage (${(memoryUsage * 100).toFixed(0)}%) is above your threshold (${(memoryThreshold * 100).toFixed(0)}%)`, `Your current memory usage (${(memoryUsage * 100).toFixed(0)}%) is above your threshold (${(memoryThreshold * 100).toFixed(0)}%)`,
disk: () => disk: () =>
`Your current disk usage: ${disk `Your current disk usage: ${disk
.map((d, idx) => `(Disk${idx}: ${(d.usage_percent * 100).toFixed(0)}%)`) .map((d, idx) => `(Disk${idx}: ${(d.usage_percent * 100).toFixed(0)}%)`)
.join( .join(", ")} is above your threshold (${(diskThreshold * 100).toFixed(0)}%)`,
", "
)} is above your threshold (${(diskThreshold * 100).toFixed(0)}%)`,
}; };
alertsToSend.push(formatAlert[type]()); alertsToSend.push(formatAlert[type]());
} }
+2 -6
View File
@@ -62,14 +62,10 @@ class SettingsService {
// Remove any old settings // Remove any old settings
await this.AppSettings.deleteMany({ version: { $exists: false } }); await this.AppSettings.deleteMany({ version: { $exists: false } });
let settings = await this.AppSettings.findOne({ singleton: true }) let settings = await this.AppSettings.findOne({ singleton: true }).select("-__v -_id -createdAt -updatedAt -singleton").lean();
.select("-__v -_id -createdAt -updatedAt -singleton")
.lean();
if (settings === null) { if (settings === null) {
await this.AppSettings.create({}); await this.AppSettings.create({});
settings = await this.AppSettings.findOne({ singleton: true }) settings = await this.AppSettings.findOne({ singleton: true }).select("-__v -_id -createdAt -updatedAt -singleton").lean();
.select("-__v -_id -createdAt -updatedAt -singleton")
.lean();
} }
return settings; return settings;
} }
+3 -9
View File
@@ -48,9 +48,7 @@ class StatusService {
if (avgResponseTime === 0) { if (avgResponseTime === 0) {
avgResponseTime = responseTime; avgResponseTime = responseTime;
} else { } else {
avgResponseTime = avgResponseTime = (avgResponseTime * (stats.totalChecks - 1) + responseTime) / stats.totalChecks;
(avgResponseTime * (stats.totalChecks - 1) + responseTime) /
stats.totalChecks;
} }
} }
stats.avgResponseTime = avgResponseTime; stats.avgResponseTime = avgResponseTime;
@@ -138,9 +136,7 @@ class StatusService {
// Monitor status changed, save prev status and update monitor // Monitor status changed, save prev status and update monitor
this.logger.info({ this.logger.info({
service: this.SERVICE_NAME, service: this.SERVICE_NAME,
message: `${monitor.name} went from ${this.getStatusString( message: `${monitor.name} went from ${this.getStatusString(monitor.status)} to ${this.getStatusString(status)}`,
monitor.status
)} to ${this.getStatusString(status)}`,
prevStatus: monitor.status, prevStatus: monitor.status,
newStatus: status, newStatus: status,
}); });
@@ -279,9 +275,7 @@ class StatusService {
message: error.message, message: error.message,
service: error.service || this.SERVICE_NAME, service: error.service || this.SERVICE_NAME,
method: error.method || "insertCheck", method: error.method || "insertCheck",
details: details: error.details || `Error inserting check for monitor: ${networkResponse?.monitorId}`,
error.details ||
`Error inserting check for monitor: ${networkResponse?.monitorId}`,
stack: error.stack, stack: error.stack,
}); });
} }
+5 -16
View File
@@ -211,23 +211,16 @@ class StringService {
} }
getWebhookUnsupportedPlatform(platform) { getWebhookUnsupportedPlatform(platform) {
return this.translationService return this.translationService.getTranslation("webhookUnsupportedPlatform").replace("{platform}", platform);
.getTranslation("webhookUnsupportedPlatform")
.replace("{platform}", platform);
} }
getWebhookSendError(platform) { getWebhookSendError(platform) {
return this.translationService return this.translationService.getTranslation("webhookSendError").replace("{platform}", platform);
.getTranslation("webhookSendError")
.replace("{platform}", platform);
} }
getMonitorStatus(name, status, url) { getMonitorStatus(name, status, url) {
const translationKey = status === true ? "monitorStatusUp" : "monitorStatusDown"; const translationKey = status === true ? "monitorStatusUp" : "monitorStatusDown";
return this.translationService return this.translationService.getTranslation(translationKey).replace("{name}", name).replace("{url}", url);
.getTranslation(translationKey)
.replace("{name}", name)
.replace("{url}", url);
} }
// Error Messages // Error Messages
@@ -378,9 +371,7 @@ class StringService {
} }
getDeletedCount(count) { getDeletedCount(count) {
return this.translationService return this.translationService.getTranslation("deletedCount").replace("{count}", count);
.getTranslation("deletedCount")
.replace("{count}", count);
} }
get pingSuccess() { get pingSuccess() {
@@ -424,9 +415,7 @@ class StringService {
} }
getDbFindMonitorById(monitorId) { getDbFindMonitorById(monitorId) {
return this.translationService return this.translationService.getTranslation("dbFindMonitorById").replace("${monitorId}", monitorId);
.getTranslation("dbFindMonitorById")
.replace("${monitorId}", monitorId);
} }
get dbUserExists() { get dbUserExists() {
+1 -3
View File
@@ -38,9 +38,7 @@ class TranslationService {
return false; return false;
} }
const files = fs const files = fs.readdirSync(this.localesDir).filter((file) => file.endsWith(".json"));
.readdirSync(this.localesDir)
.filter((file) => file.endsWith(".json"));
if (files.length === 0) { if (files.length === 0) {
return false; return false;
+6 -11
View File
@@ -30,22 +30,17 @@
<mj-section> <mj-section>
<mj-column width="100%"> <mj-column width="100%">
<mj-text> <mj-text>
<p>Hello {{name}}!</p> <p>Hello {{ name }}!</p>
<p> <p>
We hope you’re finding Checkmate helpful in monitoring your infrastructure. We hope you’re finding Checkmate helpful in monitoring your infrastructure. Your support means a lot to us, and we
Your support means a lot to us, and we <b>truly appreciate</b> having you as <b>truly appreciate</b> having you as part of our community.
part of our community.
</p> </p>
<p> <p>
If you’re happy with Checkmate, we’d love to hear about your experience! If you’re happy with Checkmate, we’d love to hear about your experience! Leaving a review on G2 helps others discover Checkmate and
Leaving a review on G2 helps others discover Checkmate and supports our supports our ongoing improvements.
ongoing improvements.
</p> </p>
G2 Link: TBD G2 Link: TBD
<p> <p>Thank you for taking the time to share your thoughts - we greatly appreciate it!</p>
Thank you for taking the time to share your thoughts - we greatly appreciate
it!
</p>
Checkmate Team Checkmate Team
</mj-text> </mj-text>
</mj-column> </mj-column>
+4 -2
View File
@@ -29,10 +29,12 @@
<mj-section> <mj-section>
<mj-column width="100%"> <mj-column width="100%">
<mj-text> <mj-text>
<p>Hello {{name}}!</p> <p>Hello {{ name }}!</p>
<p>One of the admins created an account for you on the Checkmate server.</p> <p>One of the admins created an account for you on the Checkmate server.</p>
<p>You can go ahead and create your account using this link.</p> <p>You can go ahead and create your account using this link.</p>
<p><a href="{{link}}">{{link}}</a></p> <p>
<a href="{{link}}">{{ link }}</a>
</p>
<p>Thank you.</p> <p>Thank you.</p>
</mj-text> </mj-text>
</mj-column> </mj-column>
+3 -3
View File
@@ -47,10 +47,10 @@
<mj-section> <mj-section>
<mj-column width="100%"> <mj-column width="100%">
<mj-text> <mj-text>
<p>Hello {{name}}!</p> <p>Hello {{ name }}!</p>
<p>{{monitor}} at {{url}} has the following infrastructure alerts:</p> <p>{{ monitor }} at {{ url }} has the following infrastructure alerts:</p>
{{#each alerts}} {{#each alerts}}
<p>• {{this}}</p> <p>• {{ this }}</p>
{{/each}} {{/each}}
</mj-text> </mj-text>
</mj-column> </mj-column>
+1 -1
View File
@@ -45,7 +45,7 @@
<mj-section> <mj-section>
<mj-column width="100%"> <mj-column width="100%">
<mj-text> <mj-text>
<p>Hello {{name}}!</p> <p>Hello {{ name }}!</p>
<p>There were no incidents this week. Good job!</p> <p>There were no incidents this week. Good job!</p>
<p><b>Current monitors:</b></p> <p><b>Current monitors:</b></p>
<p><b>Google:</b> 100% availability</p> <p><b>Google:</b> 100% availability</p>
+3 -3
View File
@@ -31,10 +31,10 @@
<mj-section> <mj-section>
<mj-column width="100%"> <mj-column width="100%">
<mj-text> <mj-text>
<p>Hello {{name}}!</p> <p>Hello {{ name }}!</p>
<p> <p>
You are receiving this email because a password reset request has been made You are receiving this email because a password reset request has been made for {{ email }}. Please use the link below on the site to
for {{email}}. Please use the link below on the site to reset your password. reset your password.
</p> </p>
<a href="{{url}}">Reset Password</a> <a href="{{url}}">Reset Password</a>
<p>If you didn't request this, please ignore this email.</p> <p>If you didn't request this, please ignore this email.</p>
+5 -8
View File
@@ -36,7 +36,7 @@
font-size="18px" font-size="18px"
color="red" color="red"
> >
{{monitor}} is down {{ monitor }} is down
</mj-text> </mj-text>
<mj-divider <mj-divider
border-width="2px" border-width="2px"
@@ -47,13 +47,10 @@
<mj-section> <mj-section>
<mj-column width="100%"> <mj-column width="100%">
<mj-text> <mj-text>
<p>Hello {{name}}!</p> <p>Hello {{ name }}!</p>
<p> <p>We detected an incident on one of your monitors. Your service is currently down. We'll send a message to you once it is up again.</p>
We detected an incident on one of your monitors. Your service is currently <p><b>Monitor name:</b> {{ monitor }}</p>
down. We'll send a message to you once it is up again. <p><b>URL:</b> {{ url }}</p>
</p>
<p><b>Monitor name:</b> {{monitor}}</p>
<p><b>URL:</b> {{url}}</p>
</mj-text> </mj-text>
</mj-column> </mj-column>
<mj-column width="100%"> <mj-column width="100%">
+4 -4
View File
@@ -36,7 +36,7 @@
font-size="18px" font-size="18px"
color="green" color="green"
> >
{{monitor}} is up {{ monitor }} is up
</mj-text> </mj-text>
<mj-divider <mj-divider
border-width="2px" border-width="2px"
@@ -47,10 +47,10 @@
<mj-section> <mj-section>
<mj-column width="100%"> <mj-column width="100%">
<mj-text> <mj-text>
<p>Hello {{name}}!</p> <p>Hello {{ name }}!</p>
<p>Your latest incident is resolved and your monitored service is up again.</p> <p>Your latest incident is resolved and your monitored service is up again.</p>
<p><b>Monitor name:</b> {{monitor}}</p> <p><b>Monitor name:</b> {{ monitor }}</p>
<p><b>URL:</b> {{url}}</p> <p><b>URL:</b> {{ url }}</p>
</mj-text> </mj-text>
</mj-column> </mj-column>
<mj-column width="100%"> <mj-column width="100%">
+3 -9
View File
@@ -30,15 +30,9 @@
<mj-section> <mj-section>
<mj-column width="100%"> <mj-column width="100%">
<mj-text> <mj-text>
<p>Hello {{name}}!</p> <p>Hello {{ name }}!</p>
<p> <p>Thank you for trying out Checkmate! We developed it with great care to meet our own needs, and we're excited to share it with you.</p>
Thank you for trying out Checkmate! We developed it with great care to meet <p>Checkmate is an automated way of checking whether a service such as a website or an application is available or not.</p>
our own needs, and we're excited to share it with you.
</p>
<p>
Checkmate is an automated way of checking whether a service such as a website
or an application is available or not.
</p>
<p>We hope you find our service as valuable as we do.</p> <p>We hope you find our service as valuable as we do.</p>
<p>Thank you.</p> <p>Thank you.</p>
</mj-text> </mj-text>
@@ -28,9 +28,7 @@ describe("Auth Controller - issueToken", function () {
stub = sinon.stub(jwt, "sign").throws(error); stub = sinon.stub(jwt, "sign").throws(error);
const payload = { id: "123" }; const payload = { id: "123" };
const appSettings = { jwtSecret: "my_secret" }; const appSettings = { jwtSecret: "my_secret" };
expect(() => issueToken(payload, tokenType.ACCESS_TOKEN, appSettings)).to.throw( expect(() => issueToken(payload, tokenType.ACCESS_TOKEN, appSettings)).to.throw(error);
error
);
}); });
it("should return a token if jwt.sign is successful and appSettings.jwtTTL is not defined", function () { it("should return a token if jwt.sign is successful and appSettings.jwtTTL is not defined", function () {
@@ -163,9 +161,7 @@ describe("Auth Controller - registerUser", function () {
req.db.checkSuperadmin.resolves(false); req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves(); req.db.updateAppSettings.resolves();
req.db.insertUser.resolves({ _id: "123" }); req.db.insertUser.resolves({ _id: "123" });
req.settingsService.getSettings.rejects( req.settingsService.getSettings.rejects(new Error("settingsService.getSettings error"));
new Error("settingsService.getSettings error")
);
await registerUser(req, res, next); await registerUser(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("settingsService.getSettings error"); expect(next.firstCall.args[0].message).to.equal("settingsService.getSettings error");
@@ -304,9 +300,7 @@ describe("Auth Controller - loginUser", function () {
user.comparePassword.resolves(false); user.comparePassword.resolves(false);
await loginUser(req, res, next); await loginUser(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( expect(next.firstCall.args[0].message).to.equal(errorMessages.AUTH_INCORRECT_PASSWORD);
errorMessages.AUTH_INCORRECT_PASSWORD
);
}); });
}); });
@@ -370,9 +364,7 @@ describe("Auth Controller - refreshAuthToken", function () {
}); });
it("should reject if settingsService.getSettings fails", async function () { it("should reject if settingsService.getSettings fails", async function () {
req.settingsService.getSettings.rejects( req.settingsService.getSettings.rejects(new Error("settingsService.getSettings error"));
new Error("settingsService.getSettings error")
);
await refreshAuthToken(req, res, next); await refreshAuthToken(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
@@ -475,9 +467,7 @@ describe("Auth Controller - editUser", function () {
await editUser(req, res, next); await editUser(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(401); expect(next.firstCall.args[0].status).to.equal(401);
expect(next.firstCall.args[0].message).to.equal( expect(next.firstCall.args[0].message).to.equal(errorMessages.AUTH_INCORRECT_PASSWORD);
errorMessages.AUTH_INCORRECT_PASSWORD
);
}); });
it("should edit a user if it receives a proper request", async function () { it("should edit a user if it receives a proper request", async function () {
@@ -863,8 +853,7 @@ describe("Auth Controller - deleteUser", function () {
).to.be.true; ).to.be.true;
expect(req.jobQueue.deleteJob.calledOnceWith(monitors[0])).to.be.true; expect(req.jobQueue.deleteJob.calledOnceWith(monitors[0])).to.be.true;
expect(req.db.deleteChecks.calledOnceWith("monitor_id")).to.be.true; expect(req.db.deleteChecks.calledOnceWith("monitor_id")).to.be.true;
expect(req.db.deletePageSpeedChecksByMonitorId.calledOnceWith("monitor_id")).to.be expect(req.db.deletePageSpeedChecksByMonitorId.calledOnceWith("monitor_id")).to.be.true;
.true;
expect(req.db.deleteNotificationsByMonitorId.calledOnceWith("monitor_id")).to.be.true; expect(req.db.deleteNotificationsByMonitorId.calledOnceWith("monitor_id")).to.be.true;
expect(req.db.deleteTeam.calledOnceWith("team_id")).to.be.true; expect(req.db.deleteTeam.calledOnceWith("team_id")).to.be.true;
expect(req.db.deleteAllOtherUsers.calledOnce).to.be.true; expect(req.db.deleteAllOtherUsers.calledOnce).to.be.true;
@@ -1,11 +1,4 @@
import { import { createCheck, getChecks, getTeamChecks, deleteChecks, deleteChecksByTeamId, updateChecksTTL } from "../../controllers/checkController.js";
createCheck,
getChecks,
getTeamChecks,
deleteChecks,
deleteChecksByTeamId,
updateChecksTTL,
} 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";
@@ -1,10 +1,6 @@
import sinon from "sinon"; import sinon from "sinon";
import { import { handleValidationError, handleError, fetchMonitorCertificate } from "../../controllers/controllerUtils.js";
handleValidationError,
handleError,
fetchMonitorCertificate,
} from "../../controllers/controllerUtils.js";
import { expect } from "chai"; import { expect } from "chai";
import sslChecker from "ssl-checker"; import sslChecker from "ssl-checker";
import { afterEach } from "node:test"; import { afterEach } from "node:test";
@@ -1,7 +1,4 @@
import { import { issueInvitation, inviteVerifyController } from "../../controllers/inviteController.js";
issueInvitation,
inviteVerifyController,
} 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";
@@ -623,9 +623,7 @@ describe("Monitor Controller - deleteMonitor", function () {
req.jobQueue.deleteJob.rejects(error); req.jobQueue.deleteJob.rejects(error);
await deleteMonitor(req, res, next); await deleteMonitor(req, res, next);
expect(logger.error.calledOnce).to.be.true; expect(logger.error.calledOnce).to.be.true;
expect(logger.error.firstCall.args[0].message).to.equal( expect(logger.error.firstCall.args[0].message).to.equal(`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`);
`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`
);
}); });
it("should log an error if deleteChecks throws an error", async function () { it("should log an error if deleteChecks throws an error", async function () {
@@ -635,9 +633,7 @@ describe("Monitor Controller - deleteMonitor", function () {
req.db.deleteChecks.rejects(error); req.db.deleteChecks.rejects(error);
await deleteMonitor(req, res, next); await deleteMonitor(req, res, next);
expect(logger.error.calledOnce).to.be.true; expect(logger.error.calledOnce).to.be.true;
expect(logger.error.firstCall.args[0].message).to.equal( expect(logger.error.firstCall.args[0].message).to.equal(`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`);
`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`
);
}); });
it("should log an error if deletePageSpeedChecksByMonitorId throws an error", async function () { it("should log an error if deletePageSpeedChecksByMonitorId throws an error", async function () {
@@ -647,9 +643,7 @@ describe("Monitor Controller - deleteMonitor", function () {
req.db.deletePageSpeedChecksByMonitorId.rejects(error); req.db.deletePageSpeedChecksByMonitorId.rejects(error);
await deleteMonitor(req, res, next); await deleteMonitor(req, res, next);
expect(logger.error.calledOnce).to.be.true; expect(logger.error.calledOnce).to.be.true;
expect(logger.error.firstCall.args[0].message).to.equal( expect(logger.error.firstCall.args[0].message).to.equal(`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`);
`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`
);
}); });
it("should log an error if deleteNotificationsByMonitorId throws an error", async function () { it("should log an error if deleteNotificationsByMonitorId throws an error", async function () {
@@ -659,9 +653,7 @@ describe("Monitor Controller - deleteMonitor", function () {
req.db.deleteNotificationsByMonitorId.rejects(error); req.db.deleteNotificationsByMonitorId.rejects(error);
await deleteMonitor(req, res, next); await deleteMonitor(req, res, next);
expect(logger.error.calledOnce).to.be.true; expect(logger.error.calledOnce).to.be.true;
expect(logger.error.firstCall.args[0].message).to.equal( expect(logger.error.firstCall.args[0].message).to.equal(`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`);
`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`
);
}); });
it("should return success message if all operations succeed", async function () { it("should return success message if all operations succeed", async function () {
@@ -1,10 +1,5 @@
import { afterEach } from "node:test"; import { afterEach } from "node:test";
import { import { getMetrics, getJobs, addJob, obliterateQueue } from "../../controllers/queueController.js";
getMetrics,
getJobs,
addJob,
obliterateQueue,
} from "../../controllers/queueController.js";
import { successMessages } from "../../utils/messages.js"; import { successMessages } from "../../utils/messages.js";
import sinon from "sinon"; import sinon from "sinon";
@@ -1,8 +1,5 @@
import { afterEach } from "node:test"; import { afterEach } from "node:test";
import { import { getAppSettings, updateAppSettings } from "../../controllers/settingsController.js";
getAppSettings,
updateAppSettings,
} from "../../controllers/settingsController.js";
import { successMessages } from "../../utils/messages.js"; import { successMessages } from "../../utils/messages.js";
import sinon from "sinon"; import sinon from "sinon";
@@ -1,8 +1,5 @@
import sinon from "sinon"; import sinon from "sinon";
import { import { createStatusPage, getStatusPageByUrl } from "../../controllers/statusPageController.js";
createStatusPage,
getStatusPageByUrl,
} from "../../controllers/statusPageController.js";
describe("statusPageController", function () { describe("statusPageController", function () {
let req, res, next; let req, res, next;
+1 -5
View File
@@ -216,11 +216,7 @@ describe("checkModule", function () {
const result = await getChecksCount(req); const result = await getChecksCount(req);
expect(result).to.equal(4); expect(result).to.equal(4);
expect(checkCountDocumentStub.firstCall.args[0]).to.have.all.keys( expect(checkCountDocumentStub.firstCall.args[0]).to.have.all.keys("monitorId", "createdAt", "status");
"monitorId",
"createdAt",
"status"
);
}); });
}); });
+1 -4
View File
@@ -52,10 +52,7 @@ const mockMonitor = {
}; };
describe("HardwareCheckModule", function () { describe("HardwareCheckModule", function () {
let hardwareCheckSaveStub, let hardwareCheckSaveStub, hardwareCheckCountDocumentsStub, monitorFindByIdStub, loggerStub;
hardwareCheckCountDocumentsStub,
monitorFindByIdStub,
loggerStub;
beforeEach(function () { beforeEach(function () {
loggerStub = sinon.stub(logger, "error"); loggerStub = sinon.stub(logger, "error");
+2 -9
View File
@@ -1,10 +1,6 @@
import sinon from "sinon"; import sinon from "sinon";
import InviteToken from "../../db/models/InviteToken.js"; import InviteToken from "../../db/models/InviteToken.js";
import { import { requestInviteToken, getInviteToken, getInviteTokenAndDelete } from "../../db/mongo/modules/inviteModule.js";
requestInviteToken,
getInviteToken,
getInviteTokenAndDelete,
} from "../../db/mongo/modules/inviteModule.js";
import { errorMessages } from "../../utils/messages.js"; import { errorMessages } from "../../utils/messages.js";
describe("Invite Module", function () { describe("Invite Module", function () {
@@ -15,10 +11,7 @@ describe("Invite Module", function () {
token: "123", token: "123",
}; };
const mockInviteToken = { _id: 123, time: 123 }; const mockInviteToken = { _id: 123, time: 123 };
let inviteTokenDeleteManyStub, let inviteTokenDeleteManyStub, inviteTokenSaveStub, inviteTokenFindOneStub, inviteTokenFindOneAndDeleteStub;
inviteTokenSaveStub,
inviteTokenFindOneStub,
inviteTokenFindOneAndDeleteStub;
beforeEach(function () { beforeEach(function () {
inviteTokenDeleteManyStub = sinon.stub(InviteToken, "deleteMany"); inviteTokenDeleteManyStub = sinon.stub(InviteToken, "deleteMany");
+10 -38
View File
@@ -40,15 +40,9 @@ describe("MaintenanceWindow Module", function () {
}), }),
}), }),
}); });
maintenanceWindowFindByIdAndDeleteStub = sinon.stub( maintenanceWindowFindByIdAndDeleteStub = sinon.stub(MaintenanceWindow, "findByIdAndDelete");
MaintenanceWindow,
"findByIdAndDelete"
);
maintenanceWindowDeleteManyStub = sinon.stub(MaintenanceWindow, "deleteMany"); maintenanceWindowDeleteManyStub = sinon.stub(MaintenanceWindow, "deleteMany");
maintenanceWindowFindByIdAndUpdateStub = sinon.stub( maintenanceWindowFindByIdAndUpdateStub = sinon.stub(MaintenanceWindow, "findByIdAndUpdate");
MaintenanceWindow,
"findByIdAndUpdate"
);
}); });
afterEach(function () { afterEach(function () {
@@ -110,10 +104,7 @@ describe("MaintenanceWindow Module", function () {
it("should return a list of maintenance windows and count", async function () { it("should return a list of maintenance windows and count", async function () {
maintenanceWindowCountDocumentsStub.resolves(1); maintenanceWindowCountDocumentsStub.resolves(1);
const result = await getMaintenanceWindowsByTeamId( const result = await getMaintenanceWindowsByTeamId(mockMaintenanceWindow.teamId, query);
mockMaintenanceWindow.teamId,
query
);
expect(result).to.deep.equal({ expect(result).to.deep.equal({
maintenanceWindows: mockMaintenanceWindows, maintenanceWindows: mockMaintenanceWindows,
maintenanceWindowCount: 1, maintenanceWindowCount: 1,
@@ -123,10 +114,7 @@ describe("MaintenanceWindow Module", function () {
it("should return a list of maintenance windows and count with empty query", async function () { it("should return a list of maintenance windows and count with empty query", async function () {
query = undefined; query = undefined;
maintenanceWindowCountDocumentsStub.resolves(1); maintenanceWindowCountDocumentsStub.resolves(1);
const result = await getMaintenanceWindowsByTeamId( const result = await getMaintenanceWindowsByTeamId(mockMaintenanceWindow.teamId, query);
mockMaintenanceWindow.teamId,
query
);
expect(result).to.deep.equal({ expect(result).to.deep.equal({
maintenanceWindows: mockMaintenanceWindows, maintenanceWindows: mockMaintenanceWindows,
maintenanceWindowCount: 1, maintenanceWindowCount: 1,
@@ -137,10 +125,7 @@ describe("MaintenanceWindow Module", function () {
query.page = undefined; query.page = undefined;
query.rowsPerPage = undefined; query.rowsPerPage = undefined;
maintenanceWindowCountDocumentsStub.resolves(1); maintenanceWindowCountDocumentsStub.resolves(1);
const result = await getMaintenanceWindowsByTeamId( const result = await getMaintenanceWindowsByTeamId(mockMaintenanceWindow.teamId, query);
mockMaintenanceWindow.teamId,
query
);
expect(result).to.deep.equal({ expect(result).to.deep.equal({
maintenanceWindows: mockMaintenanceWindows, maintenanceWindows: mockMaintenanceWindows,
maintenanceWindowCount: 1, maintenanceWindowCount: 1,
@@ -150,10 +135,7 @@ describe("MaintenanceWindow Module", function () {
it("should return a list of maintenance windows and count with field and desc order", async function () { it("should return a list of maintenance windows and count with field and desc order", async function () {
query.order = "desc"; query.order = "desc";
maintenanceWindowCountDocumentsStub.resolves(1); maintenanceWindowCountDocumentsStub.resolves(1);
const result = await getMaintenanceWindowsByTeamId( const result = await getMaintenanceWindowsByTeamId(mockMaintenanceWindow.teamId, query);
mockMaintenanceWindow.teamId,
query
);
expect(result).to.deep.equal({ expect(result).to.deep.equal({
maintenanceWindows: mockMaintenanceWindows, maintenanceWindows: mockMaintenanceWindows,
maintenanceWindowCount: 1, maintenanceWindowCount: 1,
@@ -163,10 +145,7 @@ describe("MaintenanceWindow Module", function () {
it("should return a list of maintenance windows and count no field", async function () { it("should return a list of maintenance windows and count no field", async function () {
query.field = undefined; query.field = undefined;
maintenanceWindowCountDocumentsStub.resolves(1); maintenanceWindowCountDocumentsStub.resolves(1);
const result = await getMaintenanceWindowsByTeamId( const result = await getMaintenanceWindowsByTeamId(mockMaintenanceWindow.teamId, query);
mockMaintenanceWindow.teamId,
query
);
expect(result).to.deep.equal({ expect(result).to.deep.equal({
maintenanceWindows: mockMaintenanceWindows, maintenanceWindows: mockMaintenanceWindows,
maintenanceWindowCount: 1, maintenanceWindowCount: 1,
@@ -187,9 +166,7 @@ describe("MaintenanceWindow Module", function () {
describe("getMaintenanceWindowsByMonitorId", function () { describe("getMaintenanceWindowsByMonitorId", function () {
it("should return a list of maintenance windows", async function () { it("should return a list of maintenance windows", async function () {
maintenanceWindowFindStub.resolves(mockMaintenanceWindows); maintenanceWindowFindStub.resolves(mockMaintenanceWindows);
const result = await getMaintenanceWindowsByMonitorId( const result = await getMaintenanceWindowsByMonitorId(mockMaintenanceWindow.monitorId);
mockMaintenanceWindow.monitorId
);
expect(result).to.deep.equal(mockMaintenanceWindows); expect(result).to.deep.equal(mockMaintenanceWindows);
}); });
@@ -225,9 +202,7 @@ describe("MaintenanceWindow Module", function () {
describe("deleteMaintenanceWindowByMonitorId", function () { describe("deleteMaintenanceWindowByMonitorId", function () {
it("should return the number of documents deleted", async function () { it("should return the number of documents deleted", async function () {
maintenanceWindowDeleteManyStub.resolves({ deletedCount: 1 }); maintenanceWindowDeleteManyStub.resolves({ deletedCount: 1 });
const result = await deleteMaintenanceWindowByMonitorId( const result = await deleteMaintenanceWindowByMonitorId(mockMaintenanceWindow.monitorId);
mockMaintenanceWindow.monitorId
);
expect(result).to.deep.equal({ deletedCount: 1 }); expect(result).to.deep.equal({ deletedCount: 1 });
}); });
@@ -263,10 +238,7 @@ describe("MaintenanceWindow Module", function () {
describe("editMaintenanceWindowById", function () { describe("editMaintenanceWindowById", function () {
it("should return the updated maintenance window", async function () { it("should return the updated maintenance window", async function () {
maintenanceWindowFindByIdAndUpdateStub.resolves(mockMaintenanceWindow); maintenanceWindowFindByIdAndUpdateStub.resolves(mockMaintenanceWindow);
const result = await editMaintenanceWindowById( const result = await editMaintenanceWindowById(mockMaintenanceWindow.id, mockMaintenanceWindow);
mockMaintenanceWindow.id,
mockMaintenanceWindow
);
expect(result).to.deep.equal(mockMaintenanceWindow); expect(result).to.deep.equal(mockMaintenanceWindow);
}); });
+20 -86
View File
@@ -120,12 +120,7 @@ describe("monitorModule", function () {
}, },
]; ];
const mockChecks = [ const mockChecks = [{ status: true }, { status: true }, { status: false }, { status: true }];
{ status: true },
{ status: true },
{ status: false },
{ status: true },
];
monitorFindStub.resolves(mockMonitors); monitorFindStub.resolves(mockMonitors);
checkFindStub.resolves(mockChecks); checkFindStub.resolves(mockChecks);
@@ -166,12 +161,7 @@ describe("monitorModule", function () {
}, },
]; ];
const mockChecks = [ const mockChecks = [{ status: true }, { status: true }, { status: false }, { status: true }];
{ status: true },
{ status: true },
{ status: false },
{ status: true },
];
monitorFindStub.resolves(mockMonitors); monitorFindStub.resolves(mockMonitors);
pageSpeedCheckFindStub.resolves(mockChecks); pageSpeedCheckFindStub.resolves(mockChecks);
@@ -212,12 +202,7 @@ describe("monitorModule", function () {
}, },
]; ];
const mockChecks = [ const mockChecks = [{ status: true }, { status: true }, { status: false }, { status: true }];
{ status: true },
{ status: true },
{ status: false },
{ status: true },
];
monitorFindStub.resolves(mockMonitors); monitorFindStub.resolves(mockMonitors);
hardwareCheckFindStub.resolves(mockChecks); hardwareCheckFindStub.resolves(mockChecks);
@@ -400,10 +385,7 @@ describe("monitorModule", function () {
}); });
it("should handle missing responseTime in checks", function () { it("should handle missing responseTime in checks", function () {
const checks = [ const checks = [{ createdAt: "2024-01-01T11:30:00Z" }, { responseTime: 200, createdAt: "2024-01-01T11:00:00Z" }];
{ createdAt: "2024-01-01T11:30:00Z" },
{ responseTime: 200, createdAt: "2024-01-01T11:00:00Z" },
];
expect(getLatestResponseTime(checks)).to.equal(0); expect(getLatestResponseTime(checks)).to.equal(0);
}); });
@@ -441,10 +423,7 @@ describe("monitorModule", function () {
}); });
it("should return 0 when no checks have responseTime", function () { it("should return 0 when no checks have responseTime", function () {
const checks = [ const checks = [{ createdAt: "2024-01-01T11:30:00Z" }, { createdAt: "2024-01-01T11:00:00Z" }];
{ createdAt: "2024-01-01T11:30:00Z" },
{ createdAt: "2024-01-01T11:00:00Z" },
];
expect(getAverageResponseTime(checks)).to.equal(0); expect(getAverageResponseTime(checks)).to.equal(0);
}); });
@@ -470,12 +449,7 @@ describe("monitorModule", function () {
}); });
it("should calculate correct percentage for mixed status checks", function () { it("should calculate correct percentage for mixed status checks", function () {
const checks = [ const checks = [{ status: true }, { status: false }, { status: true }, { status: true }];
{ status: true },
{ status: false },
{ status: true },
{ status: true },
];
// 3 up out of 4 total = 75% // 3 up out of 4 total = 75%
expect(getUptimePercentage(checks)).to.equal(75); expect(getUptimePercentage(checks)).to.equal(75);
}); });
@@ -507,23 +481,12 @@ describe("monitorModule", function () {
}); });
it("should count correct number of incidents for mixed status checks", function () { it("should count correct number of incidents for mixed status checks", function () {
const checks = [ const checks = [{ status: true }, { status: false }, { status: true }, { status: false }, { status: true }];
{ status: true },
{ status: false },
{ status: true },
{ status: false },
{ status: true },
];
expect(getIncidents(checks)).to.equal(2); expect(getIncidents(checks)).to.equal(2);
}); });
it("should handle undefined status values", function () { it("should handle undefined status values", function () {
const checks = [ const checks = [{ status: true }, { status: undefined }, { status: false }, { status: false }];
{ status: true },
{ status: undefined },
{ status: false },
{ status: false },
];
// Only counts explicit false values // Only counts explicit false values
expect(getIncidents(checks)).to.equal(2); expect(getIncidents(checks)).to.equal(2);
}); });
@@ -628,12 +591,8 @@ describe("monitorModule", function () {
); );
// Assert // Assert
expect(result.checksAll[0].createdAt).to.be.greaterThan( expect(result.checksAll[0].createdAt).to.be.greaterThan(result.checksAll[1].createdAt);
result.checksAll[1].createdAt expect(result.checksForDateRange[0].createdAt).to.be.greaterThan(result.checksForDateRange[1].createdAt);
);
expect(result.checksForDateRange[0].createdAt).to.be.greaterThan(
result.checksForDateRange[1].createdAt
);
}); });
}); });
@@ -753,10 +712,7 @@ describe("monitorModule", function () {
}); });
it("should handle checks in same time group", function () { it("should handle checks in same time group", function () {
const checksInSameHour = [ const checksInSameHour = [{ createdAt: "2024-01-15T10:15:00Z" }, { createdAt: "2024-01-15T10:45:00Z" }];
{ createdAt: "2024-01-15T10:15:00Z" },
{ createdAt: "2024-01-15T10:45:00Z" },
];
const result = groupChecksByTime(checksInSameHour, "day"); const result = groupChecksByTime(checksInSameHour, "day");
@@ -816,11 +772,7 @@ describe("monitorModule", function () {
it("should handle missing responseTime values", function () { it("should handle missing responseTime values", function () {
const mockGroup = { const mockGroup = {
time: "2024-01-15", time: "2024-01-15",
checks: [ checks: [{ status: true }, { status: false, responseTime: 200 }, { status: true, responseTime: undefined }],
{ status: true },
{ status: false, responseTime: 200 },
{ status: true, responseTime: undefined },
],
}; };
const result = calculateGroupStats(mockGroup, uptimePercentageStub); const result = calculateGroupStats(mockGroup, uptimePercentageStub);
@@ -1413,10 +1365,7 @@ describe("monitorModule", function () {
expect(Monitor.find.firstCall.args[0]).to.deep.equal({ expect(Monitor.find.firstCall.args[0]).to.deep.equal({
teamId: "team123", teamId: "team123",
$or: [ $or: [{ name: { $regex: "search", $options: "i" } }, { url: { $regex: "search", $options: "i" } }],
{ name: { $regex: "search", $options: "i" } },
{ url: { $regex: "search", $options: "i" } },
],
}); });
}); });
@@ -1816,14 +1765,9 @@ describe("monitorModule", function () {
// Assert // Assert
expect(result).to.deep.equal(mockUpdatedMonitor); expect(result).to.deep.equal(mockUpdatedMonitor);
sinon.assert.calledWith( sinon.assert.calledWith(monitorFindByIdAndUpdateStub, candidateId, expectedUpdateData, {
monitorFindByIdAndUpdateStub, new: true,
candidateId, });
expectedUpdateData,
{
new: true,
}
);
}); });
it("should return null when monitor not found", async function () { it("should return null when monitor not found", async function () {
@@ -1840,12 +1784,7 @@ describe("monitorModule", function () {
// Assert // Assert
expect(result).to.be.null; expect(result).to.be.null;
sinon.assert.calledWith( sinon.assert.calledWith(monitorFindByIdAndUpdateStub, candidateId, { name: "Updated Monitor", notifications: undefined }, { new: true });
monitorFindByIdAndUpdateStub,
candidateId,
{ name: "Updated Monitor", notifications: undefined },
{ new: true }
);
}); });
it("should remove notifications from update data", async function () { it("should remove notifications from update data", async function () {
@@ -1870,14 +1809,9 @@ describe("monitorModule", function () {
await editMonitor(candidateId, candidateMonitor); await editMonitor(candidateId, candidateMonitor);
// Assert // Assert
sinon.assert.calledWith( sinon.assert.calledWith(monitorFindByIdAndUpdateStub, candidateId, expectedUpdateData, {
monitorFindByIdAndUpdateStub, new: true,
candidateId, });
expectedUpdateData,
{
new: true,
}
);
}); });
it("should handle database errors", async function () { it("should handle database errors", async function () {
+1 -5
View File
@@ -1,10 +1,6 @@
import sinon from "sinon"; import sinon from "sinon";
import Notification from "../../db/models/Notification.js"; import Notification from "../../db/models/Notification.js";
import { import { createNotification, getNotificationsByMonitorId, deleteNotificationsByMonitorId } from "../../db/mongo/modules/notificationModule.js";
createNotification,
getNotificationsByMonitorId,
deleteNotificationsByMonitorId,
} from "../../db/mongo/modules/notificationModule.js";
describe("notificationModule", function () { describe("notificationModule", function () {
const mockNotification = { const mockNotification = {
+1 -4
View File
@@ -1,9 +1,6 @@
import sinon from "sinon"; import sinon from "sinon";
import PageSpeedCheck from "../../db/models/PageSpeedCheck.js"; import PageSpeedCheck from "../../db/models/PageSpeedCheck.js";
import { import { createPageSpeedCheck, deletePageSpeedChecksByMonitorId } from "../../db/mongo/modules/pageSpeedCheckModule.js";
createPageSpeedCheck,
deletePageSpeedChecksByMonitorId,
} from "../../db/mongo/modules/pageSpeedCheckModule.js";
const mockPageSpeedCheck = { const mockPageSpeedCheck = {
monitorId: "monitorId", monitorId: "monitorId",
+3 -14
View File
@@ -1,11 +1,7 @@
import sinon from "sinon"; import sinon from "sinon";
import RecoveryToken from "../../db/models/RecoveryToken.js"; import RecoveryToken from "../../db/models/RecoveryToken.js";
import User from "../../db/models/User.js"; import User from "../../db/models/User.js";
import { import { requestRecoveryToken, validateRecoveryToken, resetPassword } from "../../db/mongo/modules/recoveryModule.js";
requestRecoveryToken,
validateRecoveryToken,
resetPassword,
} from "../../db/mongo/modules/recoveryModule.js";
import { errorMessages } from "../../utils/messages.js"; import { errorMessages } from "../../utils/messages.js";
const mockRecoveryToken = { const mockRecoveryToken = {
@@ -44,12 +40,7 @@ const createQueryChain = (finalResult, comparePasswordResult = false) => ({
}); });
describe("recoveryModule", function () { describe("recoveryModule", function () {
let deleteManyStub, let deleteManyStub, saveStub, findOneStub, userCompareStub, userSaveStub, userFindOneStub;
saveStub,
findOneStub,
userCompareStub,
userSaveStub,
userFindOneStub;
let req, res; let req, res;
beforeEach(function () { beforeEach(function () {
@@ -153,9 +144,7 @@ describe("recoveryModule", function () {
it("should throw an error if the passwords match", async function () { it("should throw an error if the passwords match", async function () {
findOneStub.resolves(mockRecoveryToken); findOneStub.resolves(mockRecoveryToken);
saveStub.resolves(); saveStub.resolves();
userFindOneStub = sinon userFindOneStub = sinon.stub(User, "findOne").returns(createQueryChain(mockUser, true));
.stub(User, "findOne")
.returns(createQueryChain(mockUser, true));
try { try {
await resetPassword(req, res); await resetPassword(req, res);
} catch (error) { } catch (error) {
+1 -4
View File
@@ -1,8 +1,5 @@
import sinon from "sinon"; import sinon from "sinon";
import { import { getAppSettings, updateAppSettings } from "../../db/mongo/modules/settingsModule.js";
getAppSettings,
updateAppSettings,
} from "../../db/mongo/modules/settingsModule.js";
import AppSettings from "../../db/models/AppSettings.js"; import AppSettings from "../../db/models/AppSettings.js";
const mockAppSettings = { const mockAppSettings = {
+1 -4
View File
@@ -1,8 +1,5 @@
import sinon from "sinon"; import sinon from "sinon";
import { import { createStatusPage, getStatusPageByUrl } from "../../db/mongo/modules/statusPageModule.js";
createStatusPage,
getStatusPageByUrl,
} from "../../db/mongo/modules/statusPageModule.js";
import StatusPage from "../../db/models/StatusPage.js"; import StatusPage from "../../db/models/StatusPage.js";
import { errorMessages } from "../../utils/messages.js"; import { errorMessages } from "../../utils/messages.js";
+2 -12
View File
@@ -157,12 +157,7 @@ describe("userModule", function () {
select: sinon.stub().resolves(mockUser), select: sinon.stub().resolves(mockUser),
}), }),
}); });
const result = await updateUser( const result = await updateUser(req, res, parseBooleanStub, generateAvatarImageStub);
req,
res,
parseBooleanStub,
generateAvatarImageStub
);
expect(result).to.deep.equal(mockUser); expect(result).to.deep.equal(mockUser);
}); });
@@ -173,12 +168,7 @@ describe("userModule", function () {
select: sinon.stub().resolves(mockUser), select: sinon.stub().resolves(mockUser),
}), }),
}); });
const result = await updateUser( const result = await updateUser(req, res, parseBooleanStub, generateAvatarImageStub);
req,
res,
parseBooleanStub,
generateAvatarImageStub
);
expect(result).to.deep.equal(mockUser); expect(result).to.deep.equal(mockUser);
}); });
+7 -51
View File
@@ -48,15 +48,7 @@ describe("EmailService - Constructor", function () {
}); });
it("should initialize template loaders and email transporter", function () { it("should initialize template loaders and email transporter", function () {
const emailService = new EmailService( const emailService = new EmailService(settingsServiceMock, fsMock, pathMock, compileMock, mjml2htmlMock, nodemailerMock, loggerMock);
settingsServiceMock,
fsMock,
pathMock,
compileMock,
mjml2htmlMock,
nodemailerMock,
loggerMock
);
// Verify that the settingsService is assigned correctly // Verify that the settingsService is assigned correctly
expect(emailService.settingsService).to.equal(settingsServiceMock); expect(emailService.settingsService).to.equal(settingsServiceMock);
@@ -83,15 +75,7 @@ describe("EmailService - Constructor", function () {
fsMock = { fsMock = {
readFileSync: sinon.stub().throws(new Error("File read error")), readFileSync: sinon.stub().throws(new Error("File read error")),
}; };
const emailService = new EmailService( const emailService = new EmailService(settingsServiceMock, fsMock, pathMock, compileMock, mjml2htmlMock, nodemailerMock, loggerMock);
settingsServiceMock,
fsMock,
pathMock,
compileMock,
mjml2htmlMock,
nodemailerMock,
loggerMock
);
expect(loggerMock.error.called).to.be.true; expect(loggerMock.error.called).to.be.true;
expect(loggerMock.error.firstCall.args[0].message).to.equal("File read error"); expect(loggerMock.error.firstCall.args[0].message).to.equal("File read error");
}); });
@@ -139,15 +123,7 @@ describe("EmailService - buildAndSendEmail", function () {
error: sinon.stub(), error: sinon.stub(),
}; };
emailService = new EmailService( emailService = new EmailService(settingsServiceMock, fsMock, pathMock, compileMock, mjml2htmlMock, nodemailerMock, loggerMock);
settingsServiceMock,
fsMock,
pathMock,
compileMock,
mjml2htmlMock,
nodemailerMock,
loggerMock
);
}); });
afterEach(function () { afterEach(function () {
@@ -155,12 +131,7 @@ describe("EmailService - buildAndSendEmail", function () {
}); });
it("should build and send email successfully", async function () { it("should build and send email successfully", async function () {
const messageId = await emailService.buildAndSendEmail( const messageId = await emailService.buildAndSendEmail("welcomeEmailTemplate", {}, "recipient@example.com", "Welcome");
"welcomeEmailTemplate",
{},
"recipient@example.com",
"Welcome"
);
expect(messageId).to.equal("12345"); expect(messageId).to.equal("12345");
expect(nodemailerMock.createTransport().sendMail.calledOnce).to.be.true; expect(nodemailerMock.createTransport().sendMail.calledOnce).to.be.true;
@@ -169,24 +140,14 @@ describe("EmailService - buildAndSendEmail", function () {
it("should log error if building HTML fails", async function () { it("should log error if building HTML fails", async function () {
mjml2htmlMock.throws(new Error("MJML error")); mjml2htmlMock.throws(new Error("MJML error"));
const messageId = await emailService.buildAndSendEmail( const messageId = await emailService.buildAndSendEmail("welcomeEmailTemplate", {}, "recipient@example.com", "Welcome");
"welcomeEmailTemplate",
{},
"recipient@example.com",
"Welcome"
);
expect(loggerMock.error.calledOnce).to.be.true; expect(loggerMock.error.calledOnce).to.be.true;
expect(loggerMock.error.getCall(0).args[0].message).to.equal("MJML error"); expect(loggerMock.error.getCall(0).args[0].message).to.equal("MJML error");
}); });
it("should log error if sending email fails", async function () { it("should log error if sending email fails", async function () {
nodemailerMock.createTransport().sendMail.rejects(new Error("SMTP error")); nodemailerMock.createTransport().sendMail.rejects(new Error("SMTP error"));
await emailService.buildAndSendEmail( await emailService.buildAndSendEmail("welcomeEmailTemplate", {}, "recipient@example.com", "Welcome");
"welcomeEmailTemplate",
{},
"recipient@example.com",
"Welcome"
);
expect(loggerMock.error.calledOnce).to.be.true; expect(loggerMock.error.calledOnce).to.be.true;
expect(loggerMock.error.getCall(0).args[0].message).to.equal("SMTP error"); expect(loggerMock.error.getCall(0).args[0].message).to.equal("SMTP error");
}); });
@@ -195,12 +156,7 @@ describe("EmailService - buildAndSendEmail", function () {
mjml2htmlMock.throws(new Error("MJML error")); mjml2htmlMock.throws(new Error("MJML error"));
nodemailerMock.createTransport().sendMail.rejects(new Error("SMTP error")); nodemailerMock.createTransport().sendMail.rejects(new Error("SMTP error"));
const messageId = await emailService.buildAndSendEmail( const messageId = await emailService.buildAndSendEmail("welcomeEmailTemplate", {}, "recipient@example.com", "Welcome");
"welcomeEmailTemplate",
{},
"recipient@example.com",
"Welcome"
);
expect(messageId).to.be.undefined; expect(messageId).to.be.undefined;
expect(loggerMock.error.calledTwice).to.be.true; expect(loggerMock.error.calledTwice).to.be.true;
+5 -26
View File
@@ -52,13 +52,7 @@ class WorkerStub {
} }
describe("JobQueue", function () { describe("JobQueue", function () {
let settingsService, let settingsService, logger, db, networkService, statusService, notificationService, jobQueue;
logger,
db,
networkService,
statusService,
notificationService,
jobQueue;
beforeEach(async function () { beforeEach(async function () {
settingsService = { getSettings: sinon.stub() }; settingsService = { getSettings: sinon.stub() };
@@ -71,16 +65,7 @@ describe("JobQueue", function () {
getMaintenanceWindowsByMonitorId: sinon.stub().returns([]), getMaintenanceWindowsByMonitorId: sinon.stub().returns([]),
}; };
networkService = { getStatus: sinon.stub() }; networkService = { getStatus: sinon.stub() };
jobQueue = await JobQueue.createJobQueue( jobQueue = await JobQueue.createJobQueue(db, networkService, statusService, notificationService, settingsService, logger, QueueStub, WorkerStub);
db,
networkService,
statusService,
notificationService,
settingsService,
logger,
QueueStub,
WorkerStub
);
}); });
afterEach(function () { afterEach(function () {
@@ -327,9 +312,7 @@ describe("JobQueue", function () {
const handler = jobQueue.createJobHandler(); const handler = jobQueue.createJobHandler();
await handler({ data: { _id: 1 } }); await handler({ data: { _id: 1 } });
expect(logger.info.calledOnce).to.be.true; expect(logger.info.calledOnce).to.be.true;
expect(logger.info.firstCall.args[0].message).to.equal( expect(logger.info.firstCall.args[0].message).to.equal("Monitor 1 is in maintenance window");
"Monitor 1 is in maintenance window"
);
}); });
it("should return if status has not changed", async function () { it("should return if status has not changed", async function () {
@@ -362,9 +345,7 @@ describe("JobQueue", function () {
WorkerStub WorkerStub
); );
jobQueue.isInMaintenanceWindow = sinon.stub().returns(false); jobQueue.isInMaintenanceWindow = sinon.stub().returns(false);
statusService.updateStatus = sinon statusService.updateStatus = sinon.stub().returns({ statusChanged: true, prevStatus: undefined });
.stub()
.returns({ statusChanged: true, prevStatus: undefined });
const handler = jobQueue.createJobHandler(); const handler = jobQueue.createJobHandler();
await handler({ data: { _id: 1 } }); await handler({ data: { _id: 1 } });
expect(jobQueue.notificationService.handleNotifications.notCalled).to.be.true; expect(jobQueue.notificationService.handleNotifications.notCalled).to.be.true;
@@ -382,9 +363,7 @@ describe("JobQueue", function () {
WorkerStub WorkerStub
); );
jobQueue.isInMaintenanceWindow = sinon.stub().returns(false); jobQueue.isInMaintenanceWindow = sinon.stub().returns(false);
statusService.updateStatus = sinon statusService.updateStatus = sinon.stub().returns({ statusChanged: true, prevStatus: false });
.stub()
.returns({ statusChanged: true, prevStatus: false });
const handler = jobQueue.createJobHandler(); const handler = jobQueue.createJobHandler();
await handler({ data: { _id: 1 } }); await handler({ data: { _id: 1 } });
expect(jobQueue.notificationService.handleNotifications.calledOnce).to.be.true; expect(jobQueue.notificationService.handleNotifications.calledOnce).to.be.true;
+8 -24
View File
@@ -26,9 +26,7 @@ describe("Network Service", function () {
}; };
ping = { ping = {
promise: { promise: {
probe: sinon probe: sinon.stub().resolves({ response: { alive: true }, responseTime: 100, alive: true }),
.stub()
.resolves({ response: { alive: true }, responseTime: 100, alive: true }),
}, },
}; };
logger = { error: sinon.stub() }; logger = { error: sinon.stub() };
@@ -73,9 +71,7 @@ describe("Network Service", function () {
it("should return a response object if ping unsuccessful", async function () { it("should return a response object if ping unsuccessful", async function () {
const error = new Error("Test error"); const error = new Error("Test error");
networkService.timeRequest = sinon networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
.stub()
.resolves({ response: null, responseTime: 1, error });
const pingResult = await networkService.requestPing({ const pingResult = await networkService.requestPing({
data: { url: "http://test.com", _id: "123" }, data: { url: "http://test.com", _id: "123" },
}); });
@@ -113,9 +109,7 @@ describe("Network Service", function () {
it("should return a response object if http unsuccessful", async function () { it("should return a response object if http unsuccessful", async function () {
const error = new Error("Test error"); const error = new Error("Test error");
error.response = { status: 404 }; error.response = { status: 404 };
networkService.timeRequest = sinon networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
.stub()
.resolves({ response: null, responseTime: 1, error });
const job = { data: { url: "http://test.com", _id: "123", type: "http" } }; const job = { data: { url: "http://test.com", _id: "123", type: "http" } };
const httpResult = await networkService.requestHttp(job); const httpResult = await networkService.requestHttp(job);
expect(httpResult.monitorId).to.equal("123"); expect(httpResult.monitorId).to.equal("123");
@@ -128,9 +122,7 @@ describe("Network Service", function () {
it("should return a response object if http unsuccessful with unknown code", async function () { it("should return a response object if http unsuccessful with unknown code", async function () {
const error = new Error("Test error"); const error = new Error("Test error");
error.response = {}; error.response = {};
networkService.timeRequest = sinon networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
.stub()
.resolves({ response: null, responseTime: 1, error });
const job = { data: { url: "http://test.com", _id: "123", type: "http" } }; const job = { data: { url: "http://test.com", _id: "123", type: "http" } };
const httpResult = await networkService.requestHttp(job); const httpResult = await networkService.requestHttp(job);
expect(httpResult.monitorId).to.equal("123"); expect(httpResult.monitorId).to.equal("123");
@@ -167,9 +159,7 @@ describe("Network Service", function () {
it("should return a response object if pagespeed unsuccessful", async function () { it("should return a response object if pagespeed unsuccessful", async function () {
const error = new Error("Test error"); const error = new Error("Test error");
error.response = { status: 404 }; error.response = { status: 404 };
networkService.timeRequest = sinon networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
.stub()
.resolves({ response: null, responseTime: 1, error });
const job = { data: { url: "http://test.com", _id: "123", type: "pagespeed" } }; const job = { data: { url: "http://test.com", _id: "123", type: "pagespeed" } };
const pagespeedResult = await networkService.requestPagespeed(job); const pagespeedResult = await networkService.requestPagespeed(job);
expect(pagespeedResult.monitorId).to.equal("123"); expect(pagespeedResult.monitorId).to.equal("123");
@@ -182,9 +172,7 @@ describe("Network Service", function () {
it("should return a response object if pagespeed unsuccessful with an unknown code", async function () { it("should return a response object if pagespeed unsuccessful with an unknown code", async function () {
const error = new Error("Test error"); const error = new Error("Test error");
error.response = {}; error.response = {};
networkService.timeRequest = sinon networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
.stub()
.resolves({ response: null, responseTime: 1, error });
const job = { data: { url: "http://test.com", _id: "123", type: "pagespeed" } }; const job = { data: { url: "http://test.com", _id: "123", type: "pagespeed" } };
const pagespeedResult = await networkService.requestPagespeed(job); const pagespeedResult = await networkService.requestPagespeed(job);
expect(pagespeedResult.monitorId).to.equal("123"); expect(pagespeedResult.monitorId).to.equal("123");
@@ -237,9 +225,7 @@ describe("Network Service", function () {
it("should return a response object if hardware unsuccessful", async function () { it("should return a response object if hardware unsuccessful", async function () {
const error = new Error("Test error"); const error = new Error("Test error");
error.response = { status: 404 }; error.response = { status: 404 };
networkService.timeRequest = sinon networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
.stub()
.resolves({ response: null, responseTime: 1, error });
const job = { data: { url: "http://test.com", _id: "123", type: "hardware" } }; const job = { data: { url: "http://test.com", _id: "123", type: "hardware" } };
const httpResult = await networkService.requestHardware(job); const httpResult = await networkService.requestHardware(job);
expect(httpResult.monitorId).to.equal("123"); expect(httpResult.monitorId).to.equal("123");
@@ -252,9 +238,7 @@ describe("Network Service", function () {
it("should return a response object if hardware unsuccessful with unknown code", async function () { it("should return a response object if hardware unsuccessful with unknown code", async function () {
const error = new Error("Test error"); const error = new Error("Test error");
error.response = {}; error.response = {};
networkService.timeRequest = sinon networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
.stub()
.resolves({ response: null, responseTime: 1, error });
const job = { data: { url: "http://test.com", _id: "123", type: "hardware" } }; const job = { data: { url: "http://test.com", _id: "123", type: "hardware" } };
const httpResult = await networkService.requestHardware(job); const httpResult = await networkService.requestHardware(job);
expect(httpResult.monitorId).to.equal("123"); expect(httpResult.monitorId).to.equal("123");
@@ -43,10 +43,7 @@ describe("NotificationService", function () {
await notificationService.sendEmail(networkResponse, address); await notificationService.sendEmail(networkResponse, address);
expect(notificationService.emailService.buildAndSendEmail.calledOnce).to.be.true; expect(notificationService.emailService.buildAndSendEmail.calledOnce).to.be.true;
expect( expect(
notificationService.emailService.buildAndSendEmail.calledWith( notificationService.emailService.buildAndSendEmail.calledWith("serverIsUpTemplate", { monitor: "Test Monitor", url: "http://test.com" })
"serverIsUpTemplate",
{ monitor: "Test Monitor", url: "http://test.com" }
)
); );
}); });
@@ -132,22 +129,14 @@ describe("NotificationService", function () {
it("should send an email notification with Hardware Template", async function () { it("should send an email notification with Hardware Template", async function () {
emailService.buildAndSendEmail.resolves(true); emailService.buildAndSendEmail.resolves(true);
const res = await notificationService.sendHardwareEmail( const res = await notificationService.sendHardwareEmail(networkResponse, address, alerts);
networkResponse,
address,
alerts
);
expect(res).to.be.true; expect(res).to.be.true;
}); });
it("should return false if no alerts are provided", async function () { it("should return false if no alerts are provided", async function () {
alerts = []; alerts = [];
emailService.buildAndSendEmail.resolves(true); emailService.buildAndSendEmail.resolves(true);
const res = await notificationService.sendHardwareEmail( const res = await notificationService.sendHardwareEmail(networkResponse, address, alerts);
networkResponse,
address,
alerts
);
expect(res).to.be.false; expect(res).to.be.false;
}); });
}); });
@@ -172,9 +161,7 @@ describe("NotificationService", function () {
}); });
it("should handle status notifications", async function () { it("should handle status notifications", async function () {
db.getNotificationsByMonitorId.resolves([ db.getNotificationsByMonitorId.resolves([{ type: "email", address: "test@test.com" }]);
{ type: "email", address: "test@test.com" },
]);
const res = await notificationService.handleStatusNotifications(networkResponse); const res = await notificationService.handleStatusNotifications(networkResponse);
expect(res).to.be.true; expect(res).to.be.true;
}); });
@@ -247,15 +234,13 @@ describe("NotificationService", function () {
describe("it should return false if no thresholds are set", function () { describe("it should return false if no thresholds are set", function () {
it("should return false if no thresholds are set", async function () { it("should return false if no thresholds are set", async function () {
networkResponse.monitor.thresholds = undefined; networkResponse.monitor.thresholds = undefined;
const res = const res = await notificationService.handleHardwareNotifications(networkResponse);
await notificationService.handleHardwareNotifications(networkResponse);
expect(res).to.be.false; expect(res).to.be.false;
}); });
it("should return false if metrics are null", async function () { it("should return false if metrics are null", async function () {
networkResponse.payload.data = null; networkResponse.payload.data = null;
const res = const res = await notificationService.handleHardwareNotifications(networkResponse);
await notificationService.handleHardwareNotifications(networkResponse);
expect(res).to.be.false; expect(res).to.be.false;
}); });
@@ -271,8 +256,7 @@ describe("NotificationService", function () {
save: sinon.stub().resolves(), save: sinon.stub().resolves(),
}, },
]); ]);
const res = const res = await notificationService.handleHardwareNotifications(networkResponse);
await notificationService.handleHardwareNotifications(networkResponse);
expect(res).to.be.true; expect(res).to.be.true;
}); });
@@ -293,8 +277,7 @@ describe("NotificationService", function () {
usage_memory: 0.01, usage_memory: 0.01,
usage_disk: 0.01, usage_disk: 0.01,
}; };
const res = const res = await notificationService.handleHardwareNotifications(networkResponse);
await notificationService.handleHardwareNotifications(networkResponse);
expect(res).to.be.true; expect(res).to.be.true;
}); });
}); });
@@ -13,9 +13,7 @@ describe("SettingsService", function () {
sandbox.stub(process.env, "JWT_SECRET").value("secret"); sandbox.stub(process.env, "JWT_SECRET").value("secret");
sandbox.stub(process.env, "REFRESH_TOKEN_SECRET").value("refreshSecret"); sandbox.stub(process.env, "REFRESH_TOKEN_SECRET").value("refreshSecret");
sandbox.stub(process.env, "DB_TYPE").value("postgres"); sandbox.stub(process.env, "DB_TYPE").value("postgres");
sandbox sandbox.stub(process.env, "DB_CONNECTION_STRING").value("postgres://user:pass@localhost/db");
.stub(process.env, "DB_CONNECTION_STRING")
.value("postgres://user:pass@localhost/db");
sandbox.stub(process.env, "REDIS_HOST").value("localhost"); sandbox.stub(process.env, "REDIS_HOST").value("localhost");
sandbox.stub(process.env, "REDIS_PORT").value("6379"); sandbox.stub(process.env, "REDIS_PORT").value("6379");
sandbox.stub(process.env, "TOKEN_TTL").value("3600"); sandbox.stub(process.env, "TOKEN_TTL").value("3600");
+2 -6
View File
@@ -73,9 +73,7 @@ describe("StatusService", () => {
}); });
it("should return {statusChanged: true} if status has changed from down to up", async function () { it("should return {statusChanged: true} if status has changed from down to up", async function () {
statusService.db.getMonitorById = sinon statusService.db.getMonitorById = sinon.stub().returns({ status: false, save: sinon.stub() });
.stub()
.returns({ status: false, save: sinon.stub() });
const result = await statusService.updateStatus({ const result = await statusService.updateStatus({
monitorId: "test", monitorId: "test",
status: true, status: true,
@@ -87,9 +85,7 @@ describe("StatusService", () => {
}); });
it("should return {statusChanged: true} if status has changed from up to down", async function () { it("should return {statusChanged: true} if status has changed from up to down", async function () {
statusService.db.getMonitorById = sinon statusService.db.getMonitorById = sinon.stub().returns({ status: true, save: sinon.stub() });
.stub()
.returns({ status: true, save: sinon.stub() });
const result = await statusService.updateStatus({ const result = await statusService.updateStatus({
monitorId: "test", monitorId: "test",
status: false, status: false,
+1 -7
View File
@@ -51,13 +51,7 @@ describe("NormalizeData", function () {
describe("calculatePercentile", function () { describe("calculatePercentile", function () {
it("should return the lower value when upper is greater than or equal to the length of the sorted array", function () { it("should return the lower value when upper is greater than or equal to the length of the sorted array", function () {
const checks = [ const checks = [{ responseTime: 10 }, { responseTime: 20 }, { responseTime: 30 }, { responseTime: 40 }, { responseTime: 50 }];
{ responseTime: 10 },
{ responseTime: 20 },
{ responseTime: 30 },
{ responseTime: 40 },
{ responseTime: 50 },
];
const percentile = 100; const percentile = 100;
const result = calculatePercentile(checks, percentile); const result = calculatePercentile(checks, percentile);
+2 -6
View File
@@ -12,9 +12,7 @@ describe("imageProcessing - GenerateAvatarImage", function () {
// Stub the sharp function // Stub the sharp function
const toBufferStub = sinon.stub().resolves(Buffer.from("resized image buffer")); const toBufferStub = sinon.stub().resolves(Buffer.from("resized image buffer"));
const resizeStub = sinon.stub().returns({ toBuffer: toBufferStub }); const resizeStub = sinon.stub().returns({ toBuffer: toBufferStub });
const sharpStub = sinon const sharpStub = sinon.stub(sharp.prototype, "resize").returns({ toBuffer: toBufferStub });
.stub(sharp.prototype, "resize")
.returns({ toBuffer: toBufferStub });
const result = await GenerateAvatarImage(file); const result = await GenerateAvatarImage(file);
@@ -38,9 +36,7 @@ describe("imageProcessing - GenerateAvatarImage", function () {
// Stub the sharp function to throw an error // Stub the sharp function to throw an error
const toBufferStub = sinon.stub().rejects(new Error("Resizing failed")); const toBufferStub = sinon.stub().rejects(new Error("Resizing failed"));
const resizeStub = sinon.stub().returns({ toBuffer: toBufferStub }); const resizeStub = sinon.stub().returns({ toBuffer: toBufferStub });
const sharpStub = sinon const sharpStub = sinon.stub(sharp.prototype, "resize").returns({ toBuffer: toBufferStub });
.stub(sharp.prototype, "resize")
.returns({ toBuffer: toBufferStub });
try { try {
await GenerateAvatarImage(file); await GenerateAvatarImage(file);
+3 -9
View File
@@ -3,25 +3,19 @@ describe("Messages", function () {
describe("messages - errorMessages", function () { describe("messages - errorMessages", function () {
it("should have a DB_FIND_MONITOR_BY_ID function", function () { it("should have a DB_FIND_MONITOR_BY_ID function", function () {
const monitorId = "12345"; const monitorId = "12345";
expect(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)).to.equal( expect(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)).to.equal(`Monitor with id ${monitorId} not found`);
`Monitor with id ${monitorId} not found`
);
}); });
it("should have a DB_DELETE_CHECKS function", function () { it("should have a DB_DELETE_CHECKS function", function () {
const monitorId = "12345"; const monitorId = "12345";
expect(errorMessages.DB_DELETE_CHECKS(monitorId)).to.equal( expect(errorMessages.DB_DELETE_CHECKS(monitorId)).to.equal(`No checks found for monitor with id ${monitorId}`);
`No checks found for monitor with id ${monitorId}`
);
}); });
}); });
describe("messages - successMessages", function () { describe("messages - successMessages", function () {
it("should have a MONITOR_GET_BY_USER_ID function", function () { it("should have a MONITOR_GET_BY_USER_ID function", function () {
const userId = "12345"; const userId = "12345";
expect(successMessages.MONITOR_GET_BY_USER_ID(userId)).to.equal( expect(successMessages.MONITOR_GET_BY_USER_ID(userId)).to.equal(`Got monitor for ${userId} successfully"`);
`Got monitor for ${userId} successfully"`
);
}); });
// Add more tests for other success messages as needed // Add more tests for other success messages as needed
+6 -22
View File
@@ -15,9 +15,7 @@ const calculatePercentileUptimeDetails = (arr, percentile) => {
const upper = lower + 1; const upper = lower + 1;
const weight = index % 1; const weight = index % 1;
if (upper >= sorted.length) return sorted[lower].avgResponseTime; if (upper >= sorted.length) return sorted[lower].avgResponseTime;
return ( return sorted[lower].avgResponseTime * (1 - weight) + sorted[upper].avgResponseTime * weight;
sorted[lower].avgResponseTime * (1 - weight) + sorted[upper].avgResponseTime * weight
);
}; };
const NormalizeData = (checks, rangeMin, rangeMax) => { const NormalizeData = (checks, rangeMin, rangeMax) => {
@@ -28,15 +26,11 @@ const NormalizeData = (checks, rangeMin, rangeMax) => {
const normalizedChecks = checks.map((check) => { const normalizedChecks = checks.map((check) => {
const originalResponseTime = check.responseTime; const originalResponseTime = check.responseTime;
// Normalize the response time between 1 and 100 // Normalize the response time between 1 and 100
let normalizedResponseTime = let normalizedResponseTime = rangeMin + ((check.responseTime - min) * (rangeMax - rangeMin)) / (max - min);
rangeMin + ((check.responseTime - min) * (rangeMax - rangeMin)) / (max - min);
// Put a floor on the response times so we don't have extreme outliers // Put a floor on the response times so we don't have extreme outliers
// Better visuals // Better visuals
normalizedResponseTime = Math.max( normalizedResponseTime = Math.max(rangeMin, Math.min(rangeMax, normalizedResponseTime));
rangeMin,
Math.min(rangeMax, normalizedResponseTime)
);
return { return {
...check, ...check,
responseTime: normalizedResponseTime, responseTime: normalizedResponseTime,
@@ -60,15 +54,11 @@ const NormalizeDataUptimeDetails = (checks, rangeMin, rangeMax) => {
const normalizedChecks = checks.map((check) => { const normalizedChecks = checks.map((check) => {
const originalResponseTime = check.avgResponseTime; const originalResponseTime = check.avgResponseTime;
// Normalize the response time between 1 and 100 // Normalize the response time between 1 and 100
let normalizedResponseTime = let normalizedResponseTime = rangeMin + ((check.avgResponseTime - min) * (rangeMax - rangeMin)) / (max - min);
rangeMin + ((check.avgResponseTime - min) * (rangeMax - rangeMin)) / (max - min);
// Put a floor on the response times so we don't have extreme outliers // Put a floor on the response times so we don't have extreme outliers
// Better visuals // Better visuals
normalizedResponseTime = Math.max( normalizedResponseTime = Math.max(rangeMin, Math.min(rangeMax, normalizedResponseTime));
rangeMin,
Math.min(rangeMax, normalizedResponseTime)
);
return { return {
...check, ...check,
avgResponseTime: normalizedResponseTime, avgResponseTime: normalizedResponseTime,
@@ -107,10 +97,4 @@ const safelyParseFloat = (value, defaultValue = 0) => {
return parsedValue; return parsedValue;
}; };
export { export { safelyParseFloat, calculatePercentile, NormalizeData, calculatePercentileUptimeDetails, NormalizeDataUptimeDetails };
safelyParseFloat,
calculatePercentile,
NormalizeData,
calculatePercentileUptimeDetails,
NormalizeDataUptimeDetails,
};
+9 -53
View File
@@ -10,67 +10,31 @@ class AppError extends Error {
} }
} }
export const createError = ( export const createError = (message, status = 500, service = null, method = null, details = null) => {
message,
status = 500,
service = null,
method = null,
details = null
) => {
return new AppError(message, status, service, method, details); return new AppError(message, status, service, method, details);
}; };
export const createValidationError = ( export const createValidationError = (message, details = null, service = null, method = null) => {
message,
details = null,
service = null,
method = null
) => {
return createError(message, 422, service, method, details); return createError(message, 422, service, method, details);
}; };
export const createAuthError = ( export const createAuthError = (message, details = null, service = null, method = null) => {
message,
details = null,
service = null,
method = null
) => {
return createError(message, 401, service, method, details); return createError(message, 401, service, method, details);
}; };
export const createForbiddenError = ( export const createForbiddenError = (message, details = null, service = null, method = null) => {
message,
details = null,
service = null,
method = null
) => {
return createError(message, 403, service, method, details); return createError(message, 403, service, method, details);
}; };
export const createNotFoundError = ( export const createNotFoundError = (message, details = null, service = null, method = null) => {
message,
details = null,
service = null,
method = null
) => {
return createError(message, 404, service, method, details); return createError(message, 404, service, method, details);
}; };
export const createConflictError = ( export const createConflictError = (message, details = null, service = null, method = null) => {
message,
details = null,
service = null,
method = null
) => {
return createError(message, 409, service, method, details); return createError(message, 409, service, method, details);
}; };
export const createServerError = ( export const createServerError = (message, details = null, service = null, method = null) => {
message,
details = null,
service = null,
method = null
) => {
return createError(message, 500, service, method, details); return createError(message, 500, service, method, details);
}; };
@@ -81,12 +45,7 @@ export const asyncHandler = (fn, serviceName, methodName) => {
} catch (error) { } catch (error) {
// Handle validation errors // Handle validation errors
if (error.isJoi || error.name === "ValidationError") { if (error.isJoi || error.name === "ValidationError") {
const validationError = createValidationError( const validationError = createValidationError(error.message, error.details, serviceName, methodName);
error.message,
error.details,
serviceName,
methodName
);
return next(validationError); return next(validationError);
} }
@@ -107,10 +66,7 @@ export const asyncHandler = (fn, serviceName, methodName) => {
} }
// For unknown errors, create a server error // For unknown errors, create a server error
const appError = createServerError( const appError = createServerError(error.message || "An unexpected error occurred", { originalError: error.message, stack: error.stack });
error.message || "An unexpected error occurred",
{ originalError: error.message, stack: error.stack }
);
appError.service = serviceName; appError.service = serviceName;
appError.method = methodName; appError.method = methodName;
appError.stack = error.stack; // Preserve original stack appError.stack = error.stack; // Preserve original stack
+35 -42
View File
@@ -6,43 +6,41 @@ class Logger {
constructor() { constructor() {
this.logCache = []; this.logCache = [];
this.maxCacheSize = 1000; this.maxCacheSize = 1000;
const consoleFormat = format.printf( const consoleFormat = format.printf(({ level, message, service, method, details, timestamp, stack }) => {
({ level, message, service, method, details, timestamp, stack }) => { if (message instanceof Object) {
if (message instanceof Object) { message = JSON.stringify(message, null, 2);
message = JSON.stringify(message, null, 2);
}
if (details instanceof Object) {
details = JSON.stringify(details, null, 2);
}
let msg = `${timestamp} ${level}:`;
service && (msg += ` [${service}]`);
method && (msg += `(${method})`);
message && (msg += ` ${message}`);
details && (msg += ` (details: ${details})`);
if (typeof stack !== "undefined") {
const stackTrace = stack
?.split("\n")
.slice(1) // Remove first line (error message)
.map((line) => {
const match = line.match(/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);
if (match) {
return {
function: match[1],
file: match[2],
line: parseInt(match[3]),
column: parseInt(match[4]),
};
}
return line.trim();
});
stack && (msg += ` (stack: ${JSON.stringify(stackTrace, null, 2)})`);
}
return msg;
} }
);
if (details instanceof Object) {
details = JSON.stringify(details, null, 2);
}
let msg = `${timestamp} ${level}:`;
service && (msg += ` [${service}]`);
method && (msg += `(${method})`);
message && (msg += ` ${message}`);
details && (msg += ` (details: ${details})`);
if (typeof stack !== "undefined") {
const stackTrace = stack
?.split("\n")
.slice(1) // Remove first line (error message)
.map((line) => {
const match = line.match(/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);
if (match) {
return {
function: match[1],
file: match[2],
line: parseInt(match[3]),
column: parseInt(match[4]),
};
}
return line.trim();
});
stack && (msg += ` (stack: ${JSON.stringify(stackTrace, null, 2)})`);
}
return msg;
});
const logLevel = process.env.LOG_LEVEL || "info"; const logLevel = process.env.LOG_LEVEL || "info";
@@ -51,12 +49,7 @@ class Logger {
format: format.combine(format.timestamp()), format: format.combine(format.timestamp()),
transports: [ transports: [
new transports.Console({ new transports.Console({
format: format.combine( format: format.combine(format.colorize(), format.prettyPrint(), format.json(), consoleFormat),
format.colorize(),
format.prettyPrint(),
format.json(),
consoleFormat
),
}), }),
new transports.File({ new transports.File({
format: format.combine(format.json()), format: format.combine(format.json()),
+2 -8
View File
@@ -6,12 +6,7 @@
const ParseBoolean = (value) => { const ParseBoolean = (value) => {
if (value === true || value === "true") { if (value === true || value === "true") {
return true; return true;
} else if ( } else if (value === false || value === "false" || value === null || value === undefined) {
value === false ||
value === "false" ||
value === null ||
value === undefined
) {
return false; return false;
} }
}; };
@@ -21,8 +16,7 @@ const getTokenFromHeaders = (headers) => {
if (!authorizationHeader) throw new Error("No auth headers"); if (!authorizationHeader) throw new Error("No auth headers");
const parts = authorizationHeader.split(" "); const parts = authorizationHeader.split(" ");
if (parts.length !== 2 || parts[0] !== "Bearer") if (parts.length !== 2 || parts[0] !== "Bearer") throw new Error("Invalid auth headers");
throw new Error("Invalid auth headers");
return parts[1]; return parts[1];
}; };
+11 -31
View File
@@ -7,9 +7,7 @@ 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;
}; };
@@ -58,10 +56,6 @@ const registrationBodyValidation = joi.object({
inviteToken: joi.string().allow("").required(), inviteToken: joi.string().allow("").required(),
}); });
const editUserParamValidation = joi.object({
userId: joi.string().required(),
});
const editUserBodyValidation = joi.object({ const editUserBodyValidation = joi.object({
firstName: nameValidation.required(), firstName: nameValidation.required(),
lastName: nameValidation.required(), lastName: nameValidation.required(),
@@ -134,11 +128,7 @@ const getMonitorsByTeamIdQueryValidation = joi.object({
.alternatives() .alternatives()
.try( .try(
joi.string().valid("http", "ping", "pagespeed", "docker", "hardware", "port"), joi.string().valid("http", "ping", "pagespeed", "docker", "hardware", "port"),
joi joi.array().items(joi.string().valid("http", "ping", "pagespeed", "docker", "hardware", "port"))
.array()
.items(
joi.string().valid("http", "ping", "pagespeed", "docker", "hardware", "port")
)
), ),
page: joi.number(), page: joi.number(),
rowsPerPage: joi.number(), rowsPerPage: joi.number(),
@@ -454,8 +444,7 @@ const createStatusPageBodyValidation = joi.object({
.pattern(/^[a-zA-Z0-9_-]+$/) // Only allow alphanumeric, underscore, and hyphen .pattern(/^[a-zA-Z0-9_-]+$/) // Only allow alphanumeric, underscore, and hyphen
.required() .required()
.messages({ .messages({
"string.pattern.base": "string.pattern.base": "URL can only contain letters, numbers, underscores, and hyphens",
"URL can only contain letters, numbers, underscores, and hyphens",
}), }),
timezone: joi.string().optional(), timezone: joi.string().optional(),
color: joi.string().optional(), color: joi.string().optional(),
@@ -485,13 +474,9 @@ const imageValidation = joi
fieldname: joi.string().required(), fieldname: joi.string().required(),
originalname: joi.string().required(), originalname: joi.string().required(),
encoding: joi.string().required(), encoding: joi.string().required(),
mimetype: joi mimetype: joi.string().valid("image/jpeg", "image/png", "image/jpg").required().messages({
.string() "string.valid": "File must be a valid image (jpeg, jpg, or png)",
.valid("image/jpeg", "image/png", "image/jpg") }),
.required()
.messages({
"string.valid": "File must be a valid image (jpeg, jpg, or png)",
}),
size: joi.number().max(3145728).required().messages({ size: joi.number().max(3145728).required().messages({
"number.max": "File size must be less than 3MB", "number.max": "File size must be less than 3MB",
}), }),
@@ -578,15 +563,11 @@ const createNotificationBodyValidation = joi.object({
"any.required": "Notification name is required", "any.required": "Notification name is required",
}), }),
type: joi type: joi.string().valid("email", "webhook", "slack", "discord", "pager_duty").required().messages({
.string() "string.empty": "Notification type is required",
.valid("email", "webhook", "slack", "discord", "pager_duty") "any.required": "Notification type is required",
.required() "any.only": "Notification type must be email, webhook, or pager_duty",
.messages({ }),
"string.empty": "Notification type is required",
"any.required": "Notification type is required",
"any.only": "Notification type must be email, webhook, or pager_duty",
}),
address: joi.when("type", { address: joi.when("type", {
is: "email", is: "email",
@@ -659,7 +640,6 @@ export {
editMonitorBodyValidation, editMonitorBodyValidation,
pauseMonitorParamValidation, pauseMonitorParamValidation,
getMonitorURLByQueryValidation, getMonitorURLByQueryValidation,
editUserParamValidation,
editUserBodyValidation, editUserBodyValidation,
createAlertParamValidation, createAlertParamValidation,
createAlertBodyValidation, createAlertBodyValidation,