Merge pull request #1591 from bluewave-labs/feat/be/consistent-response-middleare

feat: be/consistent response middleare
This commit is contained in:
Alexander Holliday authored and GitHub committed 2025-01-20 11:48:40 -08:00
commit d91fe03acc
13 files changed
+129 -114

No files matched your search

+27 -21
View File
@@ -115,8 +115,7 @@ class AuthController {
}); });
}); });
return res.status(200).json({ res.success({
success: true,
msg: successMessages.AUTH_CREATE_USER, msg: successMessages.AUTH_CREATE_USER,
data: { user: newUser, token: token, refreshToken: refreshToken }, data: { user: newUser, token: token, refreshToken: refreshToken },
}); });
@@ -154,7 +153,9 @@ class AuthController {
// Compare password // Compare password
const match = await user.comparePassword(password); const match = await user.comparePassword(password);
if (match !== true) { if (match !== true) {
next(new Error(errorMessages.AUTH_INCORRECT_PASSWORD)); const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD);
error.status = 401;
next(error);
return; return;
} }
@@ -174,12 +175,16 @@ class AuthController {
// reset avatar image // reset avatar image
userWithoutPassword.avatarImage = user.avatarImage; userWithoutPassword.avatarImage = user.avatarImage;
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.AUTH_LOGIN_USER, msg: successMessages.AUTH_LOGIN_USER,
data: { user: userWithoutPassword, token: token, refreshToken: refreshToken }, data: {
user: userWithoutPassword,
token: token,
refreshToken: refreshToken,
},
}); });
} catch (error) { } catch (error) {
error.status = 401;
next(handleError(error, SERVICE_NAME, "loginUser")); next(handleError(error, SERVICE_NAME, "loginUser"));
} }
}; };
@@ -237,8 +242,7 @@ class AuthController {
appSettings appSettings
); );
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.AUTH_TOKEN_REFRESHED, msg: successMessages.AUTH_TOKEN_REFRESHED,
data: { user: payloadData, token: newAuthToken, refreshToken: refreshToken }, data: { user: payloadData, token: newAuthToken, refreshToken: refreshToken },
}); });
@@ -306,8 +310,7 @@ class AuthController {
} }
const updatedUser = await this.db.updateUser(req, res); const updatedUser = await this.db.updateUser(req, res);
return res.status(200).json({ res.success({
success: true,
msg: successMessages.AUTH_UPDATE_USER, msg: successMessages.AUTH_UPDATE_USER,
data: updatedUser, data: updatedUser,
}); });
@@ -328,8 +331,8 @@ class AuthController {
checkSuperadminExists = async (req, res, next) => { checkSuperadminExists = async (req, res, next) => {
try { try {
const superAdminExists = await this.db.checkSuperadmin(req, res); const superAdminExists = await this.db.checkSuperadmin(req, res);
return res.status(200).json({
success: true, return res.success({
msg: successMessages.AUTH_ADMIN_EXISTS, msg: successMessages.AUTH_ADMIN_EXISTS,
data: superAdminExists, data: superAdminExists,
}); });
@@ -375,8 +378,7 @@ class AuthController {
"Checkmate Password Reset" "Checkmate Password Reset"
); );
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN,
data: msgId, data: msgId,
}); });
@@ -406,8 +408,8 @@ class AuthController {
try { try {
await this.db.validateRecoveryToken(req, res); await this.db.validateRecoveryToken(req, res);
return res.status(200).json({
success: true, return res.success({
msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN, msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
}); });
} catch (error) { } catch (error) {
@@ -439,8 +441,8 @@ class AuthController {
const user = await this.db.resetPassword(req, res); const user = await this.db.resetPassword(req, res);
const appSettings = await this.settingsService.getSettings(); const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(user._doc, tokenType.ACCESS_TOKEN, appSettings); const token = this.issueToken(user._doc, tokenType.ACCESS_TOKEN, appSettings);
res.status(200).json({
success: true, return res.success({
msg: successMessages.AUTH_RESET_PASSWORD, msg: successMessages.AUTH_RESET_PASSWORD,
data: { user, token }, data: { user, token },
}); });
@@ -493,8 +495,8 @@ class AuthController {
} }
// 6. Delete the user by id // 6. Delete the user by id
await this.db.deleteUser(user._id); await this.db.deleteUser(user._id);
return res.status(200).json({
success: true, return res.success({
msg: successMessages.AUTH_DELETE_USER, msg: successMessages.AUTH_DELETE_USER,
}); });
} catch (error) { } catch (error) {
@@ -505,7 +507,11 @@ class AuthController {
getAllUsers = async (req, res, next) => { getAllUsers = async (req, res, next) => {
try { try {
const allUsers = await this.db.getAllUsers(req, res); const allUsers = await this.db.getAllUsers(req, res);
res.status(200).json({ success: true, msg: "Got all users", data: allUsers });
return res.success({
msg: successMessages.AUTH_GET_ALL_USERS,
data: allUsers,
});
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getAllUsersController")); next(handleError(error, SERVICE_NAME, "getAllUsersController"));
} }
+15 -13
View File
@@ -34,9 +34,11 @@ class CheckController {
try { try {
const checkData = { ...req.body }; const checkData = { ...req.body };
const check = await this.db.createCheck(checkData); const check = await this.db.createCheck(checkData);
return res
.status(200) return res.success({
.json({ success: true, msg: successMessages.CHECK_CREATE, data: check }); msg: successMessages.CHECK_CREATE,
data: check,
});
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "createCheck")); next(handleError(error, SERVICE_NAME, "createCheck"));
} }
@@ -54,8 +56,8 @@ class CheckController {
try { try {
const checks = await this.db.getChecks(req); const checks = await this.db.getChecks(req);
const checksCount = await this.db.getChecksCount(req); const checksCount = await this.db.getChecksCount(req);
return res.status(200).json({
success: true, return res.success({
msg: successMessages.CHECK_GET, msg: successMessages.CHECK_GET,
data: { checksCount, checks }, data: { checksCount, checks },
}); });
@@ -74,8 +76,8 @@ class CheckController {
} }
try { try {
const checkData = await this.db.getTeamChecks(req); const checkData = await this.db.getTeamChecks(req);
return res.status(200).json({
success: true, return res.success({
msg: successMessages.CHECK_GET, msg: successMessages.CHECK_GET,
data: checkData, data: checkData,
}); });
@@ -94,8 +96,8 @@ class CheckController {
try { try {
const deletedCount = await this.db.deleteChecks(req.params.monitorId); const deletedCount = await this.db.deleteChecks(req.params.monitorId);
return res.status(200).json({
success: true, return res.success({
msg: successMessages.CHECK_DELETE, msg: successMessages.CHECK_DELETE,
data: { deletedCount }, data: { deletedCount },
}); });
@@ -114,8 +116,8 @@ class CheckController {
try { try {
const deletedCount = await this.db.deleteChecksByTeamId(req.params.teamId); const deletedCount = await this.db.deleteChecksByTeamId(req.params.teamId);
return res.status(200).json({
success: true, return res.success({
msg: successMessages.CHECK_DELETE, msg: successMessages.CHECK_DELETE,
data: { deletedCount }, data: { deletedCount },
}); });
@@ -141,8 +143,8 @@ class CheckController {
const { teamId } = jwt.verify(token, jwtSecret); const { teamId } = jwt.verify(token, jwtSecret);
const ttl = parseInt(req.body.ttl, 10) * SECONDS_PER_DAY; const ttl = parseInt(req.body.ttl, 10) * SECONDS_PER_DAY;
await this.db.updateChecksTTL(teamId, ttl); await this.db.updateChecksTTL(teamId, ttl);
return res.status(200).json({
success: true, return res.success({
msg: successMessages.CHECK_UPDATE_TTL, msg: successMessages.CHECK_UPDATE_TTL,
}); });
} catch (error) { } catch (error) {
+7 -11
View File
@@ -13,18 +13,14 @@ const handleError = (error, serviceName, method, status = 500) => {
}; };
const fetchMonitorCertificate = async (sslChecker, monitor) => { const fetchMonitorCertificate = async (sslChecker, monitor) => {
try { const monitorUrl = new URL(monitor.url);
const monitorUrl = new URL(monitor.url); const hostname = monitorUrl.hostname;
const hostname = monitorUrl.hostname; const cert = await sslChecker(hostname);
const cert = await sslChecker(hostname); // Throw an error if no cert or if cert.validTo is not present
// Throw an error if no cert or if cert.validTo is not present if (cert?.validTo === null || cert?.validTo === undefined) {
if (cert?.validTo === null || cert?.validTo === undefined) { throw new Error("Certificate not found");
throw new Error("Certificate not found");
}
return cert;
} catch (error) {
throw error;
} }
return cert;
}; };
export { handleValidationError, handleError, fetchMonitorCertificate }; export { handleValidationError, handleError, fetchMonitorCertificate };
+10 -5
View File
@@ -7,7 +7,7 @@ import logger from "../utils/logger.js";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import { handleError, handleValidationError } from "./controllerUtils.js"; import { handleError, handleValidationError } from "./controllerUtils.js";
import { getTokenFromHeaders } from "../utils/utils.js"; import { getTokenFromHeaders } from "../utils/utils.js";
import { successMessages } from "../utils/messages.js";
const SERVICE_NAME = "inviteController"; const SERVICE_NAME = "inviteController";
class InviteController { class InviteController {
@@ -65,9 +65,10 @@ class InviteController {
}); });
}); });
return res return res.success({
.status(200) msg: successMessages.INVITE_ISSUED,
.json({ success: true, msg: "Invite sent", data: inviteToken }); data: inviteToken,
});
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "inviteController")); next(handleError(error, SERVICE_NAME, "inviteController"));
} }
@@ -83,7 +84,11 @@ class InviteController {
try { try {
const invite = await this.db.getInviteToken(req.body.token); const invite = await this.db.getInviteToken(req.body.token);
res.status(200).json({ status: "success", msg: "Invite verified", data: invite });
return res.success({
msg: successMessages.INVITE_VERIFIED,
data: invite,
});
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "inviteVerifyController")); next(handleError(error, SERVICE_NAME, "inviteVerifyController"));
} }
@@ -43,8 +43,8 @@ class MaintenanceWindowController {
}); });
}); });
await Promise.all(dbTransactions); await Promise.all(dbTransactions);
return res.status(201).json({
success: true, return res.success({
msg: successMessages.MAINTENANCE_WINDOW_CREATE, msg: successMessages.MAINTENANCE_WINDOW_CREATE,
}); });
} catch (error) { } catch (error) {
@@ -61,8 +61,8 @@ class MaintenanceWindowController {
} }
try { try {
const maintenanceWindow = await this.db.getMaintenanceWindowById(req.params.id); const maintenanceWindow = await this.db.getMaintenanceWindowById(req.params.id);
return res.status(200).json({
success: true, return res.success({
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID, msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID,
data: maintenanceWindow, data: maintenanceWindow,
}); });
@@ -88,8 +88,7 @@ class MaintenanceWindowController {
req.query req.query
); );
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM, msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM,
data: maintenanceWindows, data: maintenanceWindows,
}); });
@@ -111,8 +110,7 @@ class MaintenanceWindowController {
req.params.monitorId req.params.monitorId
); );
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_USER, msg: successMessages.MAINTENANCE_WINDOW_GET_BY_USER,
data: maintenanceWindows, data: maintenanceWindows,
}); });
@@ -130,8 +128,7 @@ class MaintenanceWindowController {
} }
try { try {
await this.db.deleteMaintenanceWindowById(req.params.id); await this.db.deleteMaintenanceWindowById(req.params.id);
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.MAINTENANCE_WINDOW_DELETE, msg: successMessages.MAINTENANCE_WINDOW_DELETE,
}); });
} catch (error) { } catch (error) {
@@ -152,8 +149,7 @@ class MaintenanceWindowController {
req.params.id, req.params.id,
req.body req.body
); );
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.MAINTENANCE_WINDOW_EDIT, msg: successMessages.MAINTENANCE_WINDOW_EDIT,
data: editedMaintenanceWindow, data: editedMaintenanceWindow,
}); });
+18 -34
View File
@@ -42,8 +42,7 @@ class MonitorController {
getAllMonitors = async (req, res, next) => { getAllMonitors = async (req, res, next) => {
try { try {
const monitors = await this.db.getAllMonitors(); const monitors = await this.db.getAllMonitors();
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.MONITOR_GET_ALL, msg: successMessages.MONITOR_GET_ALL,
data: monitors, data: monitors,
}); });
@@ -64,8 +63,7 @@ class MonitorController {
getAllMonitorsWithUptimeStats = async (req, res, next) => { getAllMonitorsWithUptimeStats = async (req, res, next) => {
try { try {
const monitors = await this.db.getAllMonitorsWithUptimeStats(); const monitors = await this.db.getAllMonitorsWithUptimeStats();
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.MONITOR_GET_ALL, msg: successMessages.MONITOR_GET_ALL,
data: monitors, data: monitors,
}); });
@@ -77,8 +75,7 @@ class MonitorController {
getUptimeDetailsById = async (req, res, next) => { getUptimeDetailsById = async (req, res, next) => {
try { try {
const monitor = await this.db.getUptimeDetailsById(req); const monitor = await this.db.getUptimeDetailsById(req);
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.MONITOR_GET_BY_ID, msg: successMessages.MONITOR_GET_BY_ID,
data: monitor, data: monitor,
}); });
@@ -107,8 +104,7 @@ class MonitorController {
try { try {
const monitorStats = await this.db.getMonitorStatsById(req); const monitorStats = await this.db.getMonitorStatsById(req);
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.MONITOR_STATS_BY_ID, msg: successMessages.MONITOR_STATS_BY_ID,
data: monitorStats, data: monitorStats,
}); });
@@ -136,8 +132,7 @@ class MonitorController {
} }
try { try {
const monitor = await this.db.getHardwareDetailsById(req); const monitor = await this.db.getHardwareDetailsById(req);
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.MONITOR_GET_BY_ID, msg: successMessages.MONITOR_GET_BY_ID,
data: monitor, data: monitor,
}); });
@@ -158,8 +153,7 @@ class MonitorController {
const monitor = await this.db.getMonitorById(monitorId); const monitor = await this.db.getMonitorById(monitorId);
const certificate = await fetchMonitorCertificate(sslChecker, monitor); const certificate = await fetchMonitorCertificate(sslChecker, monitor);
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.MONITOR_CERTIFICATE, msg: successMessages.MONITOR_CERTIFICATE,
data: { data: {
certificateDate: new Date(certificate.validTo), certificateDate: new Date(certificate.validTo),
@@ -192,8 +186,7 @@ class MonitorController {
try { try {
const monitor = await this.db.getMonitorById(req.params.monitorId); const monitor = await this.db.getMonitorById(req.params.monitorId);
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.MONITOR_GET_BY_ID, msg: successMessages.MONITOR_GET_BY_ID,
data: monitor, data: monitor,
}); });
@@ -237,8 +230,7 @@ class MonitorController {
await monitor.save(); await monitor.save();
// Add monitor to job queue // Add monitor to job queue
this.jobQueue.addJob(monitor._id, monitor); this.jobQueue.addJob(monitor._id, monitor);
return res.status(201).json({ return res.success({
success: true,
msg: successMessages.MONITOR_CREATE, msg: successMessages.MONITOR_CREATE,
data: monitor, data: monitor,
}); });
@@ -272,11 +264,9 @@ class MonitorController {
timeout: 5000, timeout: 5000,
validateStatus: () => true, validateStatus: () => true,
}); });
return res.status(200).json({ return res.success({
success: true, status: response.status,
code: response.status, msg: response.statusText,
statusText: response.statusText,
msg: `URL resolved successfully`,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "checkEndpointResolution")); next(handleError(error, SERVICE_NAME, "checkEndpointResolution"));
@@ -319,7 +309,7 @@ class MonitorController {
stack: error.stack, stack: error.stack,
}); });
} }
return res.status(200).json({ success: true, msg: successMessages.MONITOR_DELETE }); return res.success({ msg: successMessages.MONITOR_DELETE });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "deleteMonitor")); next(handleError(error, SERVICE_NAME, "deleteMonitor"));
} }
@@ -359,9 +349,7 @@ class MonitorController {
} }
}) })
); );
return res return res.success({ msg: `Deleted ${deletedCount} monitors` });
.status(200)
.json({ success: true, msg: `Deleted ${deletedCount} monitors` });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "deleteAllMonitors")); next(handleError(error, SERVICE_NAME, "deleteAllMonitors"));
} }
@@ -412,8 +400,7 @@ class MonitorController {
await this.jobQueue.deleteJob(monitorBeforeEdit); await this.jobQueue.deleteJob(monitorBeforeEdit);
// Add the new job back to the queue // Add the new job back to the queue
await this.jobQueue.addJob(editedMonitor._id, editedMonitor); await this.jobQueue.addJob(editedMonitor._id, editedMonitor);
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.MONITOR_EDIT, msg: successMessages.MONITOR_EDIT,
data: editedMonitor, data: editedMonitor,
}); });
@@ -449,8 +436,7 @@ class MonitorController {
monitor.isActive = !monitor.isActive; monitor.isActive = !monitor.isActive;
monitor.status = undefined; monitor.status = undefined;
monitor.save(); monitor.save();
return res.status(200).json({ return res.ssuccess({
success: true,
msg: monitor.isActive msg: monitor.isActive
? successMessages.MONITOR_RESUME ? successMessages.MONITOR_RESUME
: successMessages.MONITOR_PAUSE, : successMessages.MONITOR_PAUSE,
@@ -482,8 +468,7 @@ class MonitorController {
demoMonitors.map((monitor) => this.jobQueue.addJob(monitor._id, monitor)) demoMonitors.map((monitor) => this.jobQueue.addJob(monitor._id, monitor))
); );
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.MONITOR_DEMO_ADDED, msg: successMessages.MONITOR_DEMO_ADDED,
data: demoMonitors.length, data: demoMonitors.length,
}); });
@@ -502,9 +487,8 @@ class MonitorController {
try { try {
const monitors = await this.db.getMonitorsByTeamId(req); const monitors = await this.db.getMonitorsByTeamId(req);
return res.status(200).json({ return res.success({
success: true, msg: successMessages.MONITOR_GET_BY_TEAM_ID,
msg: "good",
data: monitors, data: monitors,
}); });
} catch (error) { } catch (error) {
+6 -9
View File
@@ -11,8 +11,7 @@ class JobQueueController {
getMetrics = async (req, res, next) => { getMetrics = async (req, res, next) => {
try { try {
const metrics = await this.jobQueue.getMetrics(); const metrics = await this.jobQueue.getMetrics();
res.status(200).json({ res.success({
success: true,
msg: successMessages.QUEUE_GET_METRICS, msg: successMessages.QUEUE_GET_METRICS,
data: metrics, data: metrics,
}); });
@@ -25,8 +24,7 @@ class JobQueueController {
getJobs = async (req, res, next) => { getJobs = async (req, res, next) => {
try { try {
const jobs = await this.jobQueue.getJobStats(); const jobs = await this.jobQueue.getJobStats();
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.QUEUE_GET_METRICS, msg: successMessages.QUEUE_GET_METRICS,
data: jobs, data: jobs,
}); });
@@ -39,8 +37,7 @@ class JobQueueController {
addJob = async (req, res, next) => { addJob = async (req, res, next) => {
try { try {
await this.jobQueue.addJob(Math.random().toString(36).substring(7)); await this.jobQueue.addJob(Math.random().toString(36).substring(7));
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.QUEUE_ADD_JOB, msg: successMessages.QUEUE_ADD_JOB,
}); });
} catch (error) { } catch (error) {
@@ -52,9 +49,9 @@ class JobQueueController {
obliterateQueue = async (req, res, next) => { obliterateQueue = async (req, res, next) => {
try { try {
await this.jobQueue.obliterate(); await this.jobQueue.obliterate();
return res return res.success({
.status(200) msg: successMessages.QUEUE_OBLITERATE,
.json({ success: true, msg: successMessages.QUEUE_OBLITERATE }); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "obliterateQueue")); next(handleError(error, SERVICE_NAME, "obliterateQueue"));
return; return;
+2 -4
View File
@@ -13,8 +13,7 @@ class SettingsController {
try { try {
const settings = { ...(await this.settingsService.getSettings()) }; const settings = { ...(await this.settingsService.getSettings()) };
delete settings.jwtSecret; delete settings.jwtSecret;
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.GET_APP_SETTINGS, msg: successMessages.GET_APP_SETTINGS,
data: settings, data: settings,
}); });
@@ -35,8 +34,7 @@ class SettingsController {
await this.db.updateAppSettings(req.body); await this.db.updateAppSettings(req.body);
const updatedSettings = { ...(await this.settingsService.reloadSettings()) }; const updatedSettings = { ...(await this.settingsService.reloadSettings()) };
delete updatedSettings.jwtSecret; delete updatedSettings.jwtSecret;
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.UPDATE_APP_SETTINGS, msg: successMessages.UPDATE_APP_SETTINGS,
data: updatedSettings, data: updatedSettings,
}); });
+2 -4
View File
@@ -22,8 +22,7 @@ class StatusPageController {
try { try {
const statusPage = await this.db.createStatusPage(req.body); const statusPage = await this.db.createStatusPage(req.body);
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.STATUS_PAGE_CREATE, msg: successMessages.STATUS_PAGE_CREATE,
data: statusPage, data: statusPage,
}); });
@@ -42,8 +41,7 @@ class StatusPageController {
try { try {
const { url } = req.params; const { url } = req.params;
const statusPage = await this.db.getStatusPageByUrl(url); const statusPage = await this.db.getStatusPageByUrl(url);
return res.status(200).json({ return res.success({
success: true,
msg: successMessages.STATUS_PAGE_BY_URL, msg: successMessages.STATUS_PAGE_BY_URL,
data: statusPage, data: statusPage,
}); });
+3
View File
@@ -8,6 +8,7 @@ import cors from "cors";
import logger from "./utils/logger.js"; import logger from "./utils/logger.js";
import { verifyJWT } from "./middleware/verifyJWT.js"; import { verifyJWT } from "./middleware/verifyJWT.js";
import { handleErrors } from "./middleware/handleErrors.js"; import { handleErrors } from "./middleware/handleErrors.js";
import { responseHandler } from "./middleware/responseHandler.js";
import { fileURLToPath } from "url"; import { fileURLToPath } from "url";
import AuthRoutes from "./routes/authRoute.js"; import AuthRoutes from "./routes/authRoute.js";
@@ -272,6 +273,8 @@ const startApp = async () => {
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(openApiSpec)); app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(openApiSpec));
//routes //routes
app.use(responseHandler);
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/settings", verifyJWT, settingsRoutes.getRouter());
app.use("/api/v1/invite", inviteRoutes.getRouter()); app.use("/api/v1/invite", inviteRoutes.getRouter());
+4 -1
View File
@@ -11,7 +11,10 @@ const handleErrors = (error, req, res, next) => {
method: error.method, method: error.method,
stack: error.stack, stack: error.stack,
}); });
res.status(status).json({ success: false, msg: message }); res.error({
status,
msg: message,
});
}; };
export { handleErrors }; export { handleErrors };
+20
View File
@@ -0,0 +1,20 @@
const responseHandler = (req, res, next) => {
res.success = ({ status = 200, msg = "OK", data = null }) => {
return res.status(status).json({
success: true,
msg: msg,
data: data,
});
};
res.error = ({ status = 500, msg = "Internal server error", data = null }) => {
return res.status(status).json({
success: false,
msg,
data,
});
};
next();
};
export { responseHandler };
+7
View File
@@ -73,6 +73,7 @@ const successMessages = {
ALERT_EDIT: "Alert edited successfully", ALERT_EDIT: "Alert edited successfully",
ALERT_DELETE: "Alert deleted successfully", ALERT_DELETE: "Alert deleted successfully",
// Auth Controller
AUTH_CREATE_USER: "User created successfully", AUTH_CREATE_USER: "User created successfully",
AUTH_LOGIN_USER: "User logged in successfully", AUTH_LOGIN_USER: "User logged in successfully",
AUTH_LOGOUT_USER: "User logged out successfully", AUTH_LOGOUT_USER: "User logged out successfully",
@@ -83,6 +84,11 @@ const successMessages = {
AUTH_ADMIN_CHECK: "Admin check completed successfully", AUTH_ADMIN_CHECK: "Admin check completed successfully",
AUTH_DELETE_USER: "User deleted successfully", AUTH_DELETE_USER: "User deleted successfully",
AUTH_TOKEN_REFRESHED: "Auth token is refreshed", AUTH_TOKEN_REFRESHED: "Auth token is refreshed",
AUTH_GET_ALL_USERS: "Got all users successfully",
// Invite Controller
INVITE_ISSUED: "Invite sent successfully",
INVITE_VERIFIED: "Invite verified successfully",
// Check Controller // Check Controller
CHECK_CREATE: "Check created successfully", CHECK_CREATE: "Check created successfully",
@@ -94,6 +100,7 @@ const successMessages = {
MONITOR_GET_ALL: "Got all monitors successfully", MONITOR_GET_ALL: "Got all monitors successfully",
MONITOR_STATS_BY_ID: "Got monitor stats by Id successfully", MONITOR_STATS_BY_ID: "Got monitor stats by Id successfully",
MONITOR_GET_BY_ID: "Got monitor by Id successfully", MONITOR_GET_BY_ID: "Got monitor by Id successfully",
MONITOR_GET_BY_TEAM_ID: "Got monitors by Team Id successfully",
MONITOR_GET_BY_USER_ID: (userId) => `Got monitor for ${userId} successfully"`, MONITOR_GET_BY_USER_ID: (userId) => `Got monitor for ${userId} successfully"`,
MONITOR_CREATE: "Monitor created successfully", MONITOR_CREATE: "Monitor created successfully",
MONITOR_DELETE: "Monitor deleted successfully", MONITOR_DELETE: "Monitor deleted successfully",