refactor controllers to be class based
This commit is contained in:
1 parent
8b0af64761
commit
cc40bd6006
8 files changed
+301
-283
No files matched your search
@@ -17,7 +17,15 @@ import { handleValidationError, handleError } from "./controllerUtils.js";
|
||||
const SERVICE_NAME = "authController";
|
||||
dotenv.config();
|
||||
|
||||
/**
|
||||
class AuthController {
|
||||
constructor(db, settingsService, emailService, jobQueue) {
|
||||
this.db = db;
|
||||
this.settingsService = settingsService;
|
||||
this.emailService = emailService;
|
||||
this.jobQueue = jobQueue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and returns JWT token with an arbitrary payload
|
||||
* @function
|
||||
* @param {Object} payload
|
||||
@@ -26,7 +34,7 @@ dotenv.config();
|
||||
* @returns {String}
|
||||
* @throws {Error}
|
||||
*/
|
||||
const issueToken = (payload, typeOfToken, appSettings) => {
|
||||
issueToken = (payload, typeOfToken, appSettings) => {
|
||||
try {
|
||||
const tokenTTL =
|
||||
typeOfToken === tokenType.REFRESH_TOKEN
|
||||
@@ -42,9 +50,9 @@ const issueToken = (payload, typeOfToken, appSettings) => {
|
||||
} catch (error) {
|
||||
throw handleError(error, SERVICE_NAME, "issueToken");
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Registers a new user. If the user is the first account, a JWT secret is created. If not, an invite token is required.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -56,8 +64,7 @@ const issueToken = (payload, typeOfToken, appSettings) => {
|
||||
* @returns {Object} The response object with a success status, a message indicating the creation of the user, the created user data, and a JWT token.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
const registerUser = async (req, res, next) => {
|
||||
// joi validation
|
||||
registerUser = async (req, res, next) => {
|
||||
try {
|
||||
await registrationBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
@@ -69,16 +76,16 @@ const registerUser = async (req, res, next) => {
|
||||
try {
|
||||
const { inviteToken } = req.body;
|
||||
// If superAdmin exists, a token should be attached to all further register requests
|
||||
const superAdminExists = await req.db.checkSuperadmin(req, res);
|
||||
const superAdminExists = await this.db.checkSuperadmin(req, res);
|
||||
if (superAdminExists) {
|
||||
await req.db.getInviteTokenAndDelete(inviteToken);
|
||||
await this.db.getInviteTokenAndDelete(inviteToken);
|
||||
} else {
|
||||
// This is the first account, create JWT secret to use if one is not supplied by env
|
||||
const jwtSecret = crypto.randomBytes(64).toString("hex");
|
||||
await req.db.updateAppSettings({ jwtSecret });
|
||||
await this.db.updateAppSettings({ jwtSecret });
|
||||
}
|
||||
|
||||
const newUser = await req.db.insertUser({ ...req.body }, req.file);
|
||||
const newUser = await this.db.insertUser({ ...req.body }, req.file);
|
||||
logger.info({
|
||||
message: successMessages.AUTH_CREATE_USER,
|
||||
service: SERVICE_NAME,
|
||||
@@ -89,12 +96,12 @@ const registerUser = async (req, res, next) => {
|
||||
delete userForToken.profileImage;
|
||||
delete userForToken.avatarImage;
|
||||
|
||||
const appSettings = await req.settingsService.getSettings();
|
||||
const appSettings = await this.settingsService.getSettings();
|
||||
|
||||
const token = issueToken(userForToken, tokenType.ACCESS_TOKEN, appSettings);
|
||||
const refreshToken = issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
|
||||
const token = this.issueToken(userForToken, tokenType.ACCESS_TOKEN, appSettings);
|
||||
const refreshToken = this.issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
|
||||
|
||||
req.emailService
|
||||
this.emailService
|
||||
.buildAndSendEmail(
|
||||
"welcomeEmailTemplate",
|
||||
{ name: newUser.firstName },
|
||||
@@ -118,9 +125,9 @@ const registerUser = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "registerController"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Logs in a user by validating the user's credentials and issuing a JWT token.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -132,7 +139,7 @@ const registerUser = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status, a message indicating the login of the user, the user data (without password and avatar image), and a JWT token.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or the password is incorrect.
|
||||
*/
|
||||
const loginUser = async (req, res, next) => {
|
||||
loginUser = async (req, res, next) => {
|
||||
try {
|
||||
await loginValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
@@ -144,7 +151,7 @@ const loginUser = async (req, res, next) => {
|
||||
const { email, password } = req.body;
|
||||
|
||||
// Check if user exists
|
||||
const user = await req.db.getUserByEmail(email);
|
||||
const user = await this.db.getUserByEmail(email);
|
||||
|
||||
// Compare password
|
||||
const match = await user.comparePassword(password);
|
||||
@@ -159,9 +166,13 @@ const loginUser = async (req, res, next) => {
|
||||
delete userWithoutPassword.avatarImage;
|
||||
|
||||
// Happy path, return token
|
||||
const appSettings = await req.settingsService.getSettings();
|
||||
const token = issueToken(userWithoutPassword, tokenType.ACCESS_TOKEN, appSettings);
|
||||
const refreshToken = issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
|
||||
const appSettings = await this.settingsService.getSettings();
|
||||
const token = this.issueToken(
|
||||
userWithoutPassword,
|
||||
tokenType.ACCESS_TOKEN,
|
||||
appSettings
|
||||
);
|
||||
const refreshToken = this.issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
|
||||
// reset avatar image
|
||||
userWithoutPassword.avatarImage = user.avatarImage;
|
||||
|
||||
@@ -173,9 +184,9 @@ const loginUser = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "loginUser"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Generates new auth token if the refresh token is valid
|
||||
* @async
|
||||
* @param {Express.Request} req - The Express request object.
|
||||
@@ -185,7 +196,7 @@ const loginUser = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status, a message indicating new auth token is generated.
|
||||
* @throws {Error} If there is an error during the process such as any of the token is not received
|
||||
*/
|
||||
const refreshAuthToken = async (req, res, next) => {
|
||||
refreshAuthToken = async (req, res, next) => {
|
||||
try {
|
||||
// check for refreshToken
|
||||
const refreshToken = req.headers["x-refresh-token"];
|
||||
@@ -200,7 +211,7 @@ const refreshAuthToken = async (req, res, next) => {
|
||||
}
|
||||
|
||||
// Verify refresh token
|
||||
const appSettings = await req.settingsService.getSettings();
|
||||
const appSettings = await this.settingsService.getSettings();
|
||||
const { refreshTokenSecret } = appSettings;
|
||||
jwt.verify(refreshToken, refreshTokenSecret, async (refreshErr, refreshDecoded) => {
|
||||
if (refreshErr) {
|
||||
@@ -217,12 +228,16 @@ const refreshAuthToken = async (req, res, next) => {
|
||||
});
|
||||
// Refresh token is valid and unexpired, generate new access token
|
||||
const oldAuthToken = getTokenFromHeaders(req.headers);
|
||||
const { jwtSecret } = await req.settingsService.getSettings();
|
||||
const { jwtSecret } = await this.settingsService.getSettings();
|
||||
const payloadData = jwt.verify(oldAuthToken, jwtSecret, { ignoreExpiration: true });
|
||||
// delete old token related data
|
||||
delete payloadData.iat;
|
||||
delete payloadData.exp;
|
||||
const newAuthToken = issueToken(payloadData, tokenType.ACCESS_TOKEN, appSettings);
|
||||
const newAuthToken = this.issueToken(
|
||||
payloadData,
|
||||
tokenType.ACCESS_TOKEN,
|
||||
appSettings
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
@@ -232,9 +247,8 @@ const refreshAuthToken = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "refreshAuthToken"));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
};
|
||||
/**
|
||||
* Edits a user's information. If the user wants to change their password, the current password is checked before updating to the new password.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -248,7 +262,7 @@ const refreshAuthToken = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status, a message indicating the update of the user, and the updated user data.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422), the user is unauthorized (401), or the password is incorrect (403).
|
||||
*/
|
||||
const editUser = async (req, res, next) => {
|
||||
editUser = async (req, res, next) => {
|
||||
try {
|
||||
await editUserParamValidation.validateAsync(req.params);
|
||||
await editUserBodyValidation.validateAsync(req.body);
|
||||
@@ -273,12 +287,12 @@ const editUser = async (req, res, next) => {
|
||||
// Get token from headers
|
||||
const token = getTokenFromHeaders(req.headers);
|
||||
// Get email from token
|
||||
const { jwtSecret } = req.settingsService.getSettings();
|
||||
const { jwtSecret } = this.settingsService.getSettings();
|
||||
const { email } = jwt.verify(token, jwtSecret);
|
||||
// Add user email to body for DB operation
|
||||
req.body.email = email;
|
||||
// Get user
|
||||
const user = await req.db.getUserByEmail(email);
|
||||
const user = await this.db.getUserByEmail(email);
|
||||
// Compare passwords
|
||||
const match = await user.comparePassword(req.body.password);
|
||||
// If not a match, throw a 403
|
||||
@@ -293,7 +307,7 @@ const editUser = async (req, res, next) => {
|
||||
req.body.password = req.body.newPassword;
|
||||
}
|
||||
|
||||
const updatedUser = await req.db.updateUser(req, res);
|
||||
const updatedUser = await this.db.updateUser(req, res);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.AUTH_UPDATE_USER,
|
||||
@@ -302,9 +316,9 @@ const editUser = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "userEditController"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Checks if a superadmin account exists in the database.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -313,9 +327,9 @@ const editUser = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status, a message indicating the existence of a superadmin, and a boolean indicating the existence of a superadmin.
|
||||
* @throws {Error} If there is an error during the process.
|
||||
*/
|
||||
const checkSuperadminExists = async (req, res, next) => {
|
||||
checkSuperadminExists = async (req, res, next) => {
|
||||
try {
|
||||
const superAdminExists = await req.db.checkSuperadmin(req, res);
|
||||
const superAdminExists = await this.db.checkSuperadmin(req, res);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.AUTH_ADMIN_EXISTS,
|
||||
@@ -324,9 +338,8 @@ const checkSuperadminExists = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "checkSuperadminController"));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
};
|
||||
/**
|
||||
* Requests a recovery token for a user. The user's email is validated and a recovery token is created and sent via email.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -337,7 +350,7 @@ const checkSuperadminExists = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status, a message indicating the creation of the recovery token, and the message ID of the sent email.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
const requestRecovery = async (req, res, next) => {
|
||||
requestRecovery = async (req, res, next) => {
|
||||
try {
|
||||
await recoveryValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
@@ -348,12 +361,12 @@ const requestRecovery = async (req, res, next) => {
|
||||
|
||||
try {
|
||||
const { email } = req.body;
|
||||
const user = await req.db.getUserByEmail(email);
|
||||
const recoveryToken = await req.db.requestRecoveryToken(req, res);
|
||||
const user = await this.db.getUserByEmail(email);
|
||||
const recoveryToken = await this.db.requestRecoveryToken(req, res);
|
||||
const name = user.firstName;
|
||||
const { clientHost } = req.settingsService.getSettings();
|
||||
const { clientHost } = this.settingsService.getSettings();
|
||||
const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
|
||||
const msgId = await req.emailService.buildAndSendEmail(
|
||||
const msgId = await this.emailService.buildAndSendEmail(
|
||||
"passwordResetTemplate",
|
||||
{
|
||||
name,
|
||||
@@ -372,9 +385,8 @@ const requestRecovery = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "recoveryRequestController"));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
};
|
||||
/**
|
||||
* Validates a recovery token. The recovery token is validated and if valid, a success message is returned.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -385,7 +397,7 @@ const requestRecovery = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status and a message indicating the validation of the recovery token.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
const validateRecovery = async (req, res, next) => {
|
||||
validateRecovery = async (req, res, next) => {
|
||||
try {
|
||||
await recoveryTokenValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
@@ -395,7 +407,7 @@ const validateRecovery = async (req, res, next) => {
|
||||
}
|
||||
|
||||
try {
|
||||
await req.db.validateRecoveryToken(req, res);
|
||||
await this.db.validateRecoveryToken(req, res);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
|
||||
@@ -403,9 +415,9 @@ const validateRecovery = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "validateRecoveryTokenController"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Resets a user's password. The new password is validated and if valid, the user's password is updated in the database and a new JWT token is issued.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -417,7 +429,7 @@ const validateRecovery = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status, a message indicating the reset of the password, the updated user data (without password and avatar image), and a new JWT token.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
const resetPassword = async (req, res, next) => {
|
||||
resetPassword = async (req, res, next) => {
|
||||
try {
|
||||
await newPasswordValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
@@ -426,9 +438,9 @@ const resetPassword = async (req, res, next) => {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const user = await req.db.resetPassword(req, res);
|
||||
const appSettings = await req.settingsService.getSettings();
|
||||
const token = issueToken(user._doc, tokenType.ACCESS_TOKEN, appSettings);
|
||||
const user = await this.db.resetPassword(req, res);
|
||||
const appSettings = await this.settingsService.getSettings();
|
||||
const token = this.issueToken(user._doc, tokenType.ACCESS_TOKEN, appSettings);
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.AUTH_RESET_PASSWORD,
|
||||
@@ -437,9 +449,9 @@ const resetPassword = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "resetPasswordController"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Deletes a user and all associated monitors, checks, and alerts.
|
||||
*
|
||||
* @param {Object} req - The request object.
|
||||
@@ -448,17 +460,17 @@ const resetPassword = async (req, res, next) => {
|
||||
* @returns {Object} The response object with success status and message.
|
||||
* @throws {Error} If user validation fails or user is not found in the database.
|
||||
*/
|
||||
const deleteUser = async (req, res, next) => {
|
||||
deleteUser = async (req, res, next) => {
|
||||
try {
|
||||
const token = getTokenFromHeaders(req.headers);
|
||||
const decodedToken = jwt.decode(token);
|
||||
const { email } = decodedToken;
|
||||
|
||||
// Check if the user exists
|
||||
const user = await req.db.getUserByEmail(email);
|
||||
const user = await this.db.getUserByEmail(email);
|
||||
// 1. Find all the monitors associated with the team ID if superadmin
|
||||
|
||||
const result = await req.db.getMonitorsByTeamId({
|
||||
const result = await this.db.getMonitorsByTeamId({
|
||||
params: { teamId: user.teamId },
|
||||
});
|
||||
|
||||
@@ -467,22 +479,22 @@ const deleteUser = async (req, res, next) => {
|
||||
result?.monitors.length > 0 &&
|
||||
(await Promise.all(
|
||||
result.monitors.map(async (monitor) => {
|
||||
await req.jobQueue.deleteJob(monitor);
|
||||
await req.db.deleteChecks(monitor._id);
|
||||
await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
|
||||
await req.db.deleteNotificationsByMonitorId(monitor._id);
|
||||
await this.jobQueue.deleteJob(monitor);
|
||||
await this.db.deleteChecks(monitor._id);
|
||||
await this.db.deletePageSpeedChecksByMonitorId(monitor._id);
|
||||
await this.db.deleteNotificationsByMonitorId(monitor._id);
|
||||
})
|
||||
));
|
||||
|
||||
// 3. Delete team
|
||||
await req.db.deleteTeam(user.teamId);
|
||||
await this.db.deleteTeam(user.teamId);
|
||||
// 4. Delete all other team members
|
||||
await req.db.deleteAllOtherUsers();
|
||||
await this.db.deleteAllOtherUsers();
|
||||
// 5. Delete each monitor
|
||||
await req.db.deleteMonitorsByUserId(user._id);
|
||||
await this.db.deleteMonitorsByUserId(user._id);
|
||||
}
|
||||
// 6. Delete the user by id
|
||||
await req.db.deleteUser(user._id);
|
||||
await this.db.deleteUser(user._id);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.AUTH_DELETE_USER,
|
||||
@@ -490,27 +502,16 @@ const deleteUser = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteUserController"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const getAllUsers = async (req, res, next) => {
|
||||
getAllUsers = async (req, res, next) => {
|
||||
try {
|
||||
const allUsers = await req.db.getAllUsers(req, res);
|
||||
const allUsers = await this.db.getAllUsers(req, res);
|
||||
res.status(200).json({ success: true, msg: "Got all users", data: allUsers });
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getAllUsersController"));
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
issueToken,
|
||||
registerUser,
|
||||
loginUser,
|
||||
refreshAuthToken,
|
||||
editUser,
|
||||
checkSuperadminExists,
|
||||
requestRecovery,
|
||||
validateRecovery,
|
||||
resetPassword,
|
||||
deleteUser,
|
||||
getAllUsers,
|
||||
};
|
||||
export default AuthController;
|
||||
@@ -16,7 +16,13 @@ import { handleValidationError, handleError } from "./controllerUtils.js";
|
||||
|
||||
const SERVICE_NAME = "checkController";
|
||||
|
||||
const createCheck = async (req, res, next) => {
|
||||
class CheckController {
|
||||
constructor(db, settingsService) {
|
||||
this.db = db;
|
||||
this.settingsService = settingsService;
|
||||
}
|
||||
|
||||
createCheck = async (req, res, next) => {
|
||||
try {
|
||||
await createCheckParamValidation.validateAsync(req.params);
|
||||
await createCheckBodyValidation.validateAsync(req.body);
|
||||
@@ -27,16 +33,16 @@ const createCheck = async (req, res, next) => {
|
||||
|
||||
try {
|
||||
const checkData = { ...req.body };
|
||||
const check = await req.db.createCheck(checkData);
|
||||
const check = await this.db.createCheck(checkData);
|
||||
return res
|
||||
.status(200)
|
||||
.json({ success: true, msg: successMessages.CHECK_CREATE, data: check });
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "createCheck"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const getChecks = async (req, res, next) => {
|
||||
getChecks = async (req, res, next) => {
|
||||
try {
|
||||
await getChecksParamValidation.validateAsync(req.params);
|
||||
await getChecksQueryValidation.validateAsync(req.query);
|
||||
@@ -46,8 +52,8 @@ const getChecks = async (req, res, next) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const checks = await req.db.getChecks(req);
|
||||
const checksCount = await req.db.getChecksCount(req);
|
||||
const checks = await this.db.getChecks(req);
|
||||
const checksCount = await this.db.getChecksCount(req);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_GET,
|
||||
@@ -56,9 +62,9 @@ const getChecks = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getChecks"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const getTeamChecks = async (req, res, next) => {
|
||||
getTeamChecks = async (req, res, next) => {
|
||||
try {
|
||||
await getTeamChecksParamValidation.validateAsync(req.params);
|
||||
await getTeamChecksQueryValidation.validateAsync(req.query);
|
||||
@@ -67,7 +73,7 @@ const getTeamChecks = async (req, res, next) => {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const checkData = await req.db.getTeamChecks(req);
|
||||
const checkData = await this.db.getTeamChecks(req);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_GET,
|
||||
@@ -76,9 +82,9 @@ const getTeamChecks = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getTeamChecks"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const deleteChecks = async (req, res, next) => {
|
||||
deleteChecks = async (req, res, next) => {
|
||||
try {
|
||||
await deleteChecksParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
@@ -87,7 +93,7 @@ const deleteChecks = async (req, res, next) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const deletedCount = await req.db.deleteChecks(req.params.monitorId);
|
||||
const deletedCount = await this.db.deleteChecks(req.params.monitorId);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_DELETE,
|
||||
@@ -96,9 +102,9 @@ const deleteChecks = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteChecks"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const deleteChecksByTeamId = async (req, res, next) => {
|
||||
deleteChecksByTeamId = async (req, res, next) => {
|
||||
try {
|
||||
await deleteChecksByTeamIdParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
@@ -107,7 +113,7 @@ const deleteChecksByTeamId = async (req, res, next) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const deletedCount = await req.db.deleteChecksByTeamId(req.params.teamId);
|
||||
const deletedCount = await this.db.deleteChecksByTeamId(req.params.teamId);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_DELETE,
|
||||
@@ -116,9 +122,9 @@ const deleteChecksByTeamId = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteChecksByTeamId"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const updateChecksTTL = async (req, res, next) => {
|
||||
updateChecksTTL = async (req, res, next) => {
|
||||
const SECONDS_PER_DAY = 86400;
|
||||
|
||||
try {
|
||||
@@ -131,10 +137,10 @@ const updateChecksTTL = async (req, res, next) => {
|
||||
try {
|
||||
// Get user's teamId
|
||||
const token = getTokenFromHeaders(req.headers);
|
||||
const { jwtSecret } = req.settingsService.getSettings();
|
||||
const { jwtSecret } = this.settingsService.getSettings();
|
||||
const { teamId } = jwt.verify(token, jwtSecret);
|
||||
const ttl = parseInt(req.body.ttl, 10) * SECONDS_PER_DAY;
|
||||
await req.db.updateChecksTTL(teamId, ttl);
|
||||
await this.db.updateChecksTTL(teamId, ttl);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_UPDATE_TTL,
|
||||
@@ -142,13 +148,6 @@ const updateChecksTTL = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "updateTTL"));
|
||||
}
|
||||
};
|
||||
|
||||
export {
|
||||
createCheck,
|
||||
getChecks,
|
||||
getTeamChecks,
|
||||
deleteChecks,
|
||||
deleteChecksByTeamId,
|
||||
updateChecksTTL,
|
||||
};
|
||||
};
|
||||
}
|
||||
export default CheckController;
|
||||
@@ -4,16 +4,20 @@ import {
|
||||
inviteVerificationBodyValidation,
|
||||
} from "../validation/joi.js";
|
||||
import logger from "../utils/logger.js";
|
||||
import dotenv from "dotenv";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { handleError, handleValidationError } from "./controllerUtils.js";
|
||||
import { getTokenFromHeaders } from "../utils/utils.js";
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const SERVICE_NAME = "inviteController";
|
||||
|
||||
/**
|
||||
class InviteController {
|
||||
constructor(db, settingsService, emailService) {
|
||||
this.db = db;
|
||||
this.settingsService = settingsService;
|
||||
this.emailService = emailService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Issues an invitation to a new user. Only admins can invite new users. An invitation token is created and sent via email.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -26,7 +30,7 @@ const SERVICE_NAME = "inviteController";
|
||||
* @returns {Object} The response object with a success status, a message indicating the sending of the invitation, and the invitation token.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
const issueInvitation = async (req, res, next) => {
|
||||
issueInvitation = async (req, res, next) => {
|
||||
try {
|
||||
// Only admins can invite
|
||||
const token = getTokenFromHeaders(req.headers);
|
||||
@@ -40,9 +44,9 @@ const issueInvitation = async (req, res, next) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const inviteToken = await req.db.requestInviteToken({ ...req.body });
|
||||
const { clientHost } = req.settingsService.getSettings();
|
||||
req.emailService
|
||||
const inviteToken = await this.db.requestInviteToken({ ...req.body });
|
||||
const { clientHost } = this.settingsService.getSettings();
|
||||
this.emailService
|
||||
.buildAndSendEmail(
|
||||
"employeeActivationTemplate",
|
||||
{
|
||||
@@ -61,13 +65,15 @@ const issueInvitation = async (req, res, next) => {
|
||||
});
|
||||
});
|
||||
|
||||
return res.status(200).json({ success: true, msg: "Invite sent", data: inviteToken });
|
||||
return res
|
||||
.status(200)
|
||||
.json({ success: true, msg: "Invite sent", data: inviteToken });
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "inviteController"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const inviteVerifyController = async (req, res, next) => {
|
||||
inviteVerifyController = async (req, res, next) => {
|
||||
try {
|
||||
await inviteVerificationBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
@@ -76,11 +82,12 @@ const inviteVerifyController = async (req, res, next) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const invite = await req.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 });
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "inviteVerifyController"));
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export { issueInvitation, inviteVerifyController };
|
||||
export default InviteController;
|
||||
@@ -11,10 +11,15 @@ import jwt from "jsonwebtoken";
|
||||
import { getTokenFromHeaders } from "../utils/utils.js";
|
||||
import { successMessages } from "../utils/messages.js";
|
||||
import { handleValidationError, handleError } from "./controllerUtils.js";
|
||||
|
||||
const SERVICE_NAME = "maintenanceWindowController";
|
||||
|
||||
const createMaintenanceWindows = async (req, res, next) => {
|
||||
class MaintenanceWindowController {
|
||||
constructor(db, settingsService) {
|
||||
this.db = db;
|
||||
this.settingsService = settingsService;
|
||||
}
|
||||
|
||||
createMaintenanceWindows = async (req, res, next) => {
|
||||
try {
|
||||
await createMaintenanceWindowBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
@@ -23,11 +28,11 @@ const createMaintenanceWindows = async (req, res, next) => {
|
||||
}
|
||||
try {
|
||||
const token = getTokenFromHeaders(req.headers);
|
||||
const { jwtSecret } = req.settingsService.getSettings();
|
||||
const { jwtSecret } = this.settingsService.getSettings();
|
||||
const { teamId } = jwt.verify(token, jwtSecret);
|
||||
const monitorIds = req.body.monitors;
|
||||
const dbTransactions = monitorIds.map((monitorId) => {
|
||||
return req.db.createMaintenanceWindow({
|
||||
return this.db.createMaintenanceWindow({
|
||||
teamId,
|
||||
monitorId,
|
||||
name: req.body.name,
|
||||
@@ -45,9 +50,9 @@ const createMaintenanceWindows = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "createMaintenanceWindow"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const getMaintenanceWindowById = async (req, res, next) => {
|
||||
getMaintenanceWindowById = async (req, res, next) => {
|
||||
try {
|
||||
await getMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
@@ -55,7 +60,7 @@ const getMaintenanceWindowById = async (req, res, next) => {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const maintenanceWindow = await req.db.getMaintenanceWindowById(req.params.id);
|
||||
const maintenanceWindow = await this.db.getMaintenanceWindowById(req.params.id);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID,
|
||||
@@ -64,9 +69,9 @@ const getMaintenanceWindowById = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowById"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const getMaintenanceWindowsByTeamId = async (req, res, next) => {
|
||||
getMaintenanceWindowsByTeamId = async (req, res, next) => {
|
||||
try {
|
||||
await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
@@ -76,9 +81,9 @@ const getMaintenanceWindowsByTeamId = async (req, res, next) => {
|
||||
|
||||
try {
|
||||
const token = getTokenFromHeaders(req.headers);
|
||||
const { jwtSecret } = req.settingsService.getSettings();
|
||||
const { jwtSecret } = this.settingsService.getSettings();
|
||||
const { teamId } = jwt.verify(token, jwtSecret);
|
||||
const maintenanceWindows = await req.db.getMaintenanceWindowsByTeamId(
|
||||
const maintenanceWindows = await this.db.getMaintenanceWindowsByTeamId(
|
||||
teamId,
|
||||
req.query
|
||||
);
|
||||
@@ -91,9 +96,9 @@ const getMaintenanceWindowsByTeamId = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByUserId"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const getMaintenanceWindowsByMonitorId = async (req, res, next) => {
|
||||
getMaintenanceWindowsByMonitorId = async (req, res, next) => {
|
||||
try {
|
||||
await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
@@ -102,7 +107,7 @@ const getMaintenanceWindowsByMonitorId = async (req, res, next) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const maintenanceWindows = await req.db.getMaintenanceWindowsByMonitorId(
|
||||
const maintenanceWindows = await this.db.getMaintenanceWindowsByMonitorId(
|
||||
req.params.monitorId
|
||||
);
|
||||
|
||||
@@ -114,9 +119,9 @@ const getMaintenanceWindowsByMonitorId = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByMonitorId"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const deleteMaintenanceWindow = async (req, res, next) => {
|
||||
deleteMaintenanceWindow = async (req, res, next) => {
|
||||
try {
|
||||
await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
@@ -124,7 +129,7 @@ const deleteMaintenanceWindow = async (req, res, next) => {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await req.db.deleteMaintenanceWindowById(req.params.id);
|
||||
await this.db.deleteMaintenanceWindowById(req.params.id);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_DELETE,
|
||||
@@ -132,9 +137,9 @@ const deleteMaintenanceWindow = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteMaintenanceWindow"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const editMaintenanceWindow = async (req, res, next) => {
|
||||
editMaintenanceWindow = async (req, res, next) => {
|
||||
try {
|
||||
await editMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
||||
await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body);
|
||||
@@ -143,7 +148,7 @@ const editMaintenanceWindow = async (req, res, next) => {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const editedMaintenanceWindow = await req.db.editMaintenanceWindowById(
|
||||
const editedMaintenanceWindow = await this.db.editMaintenanceWindowById(
|
||||
req.params.id,
|
||||
req.body
|
||||
);
|
||||
@@ -155,13 +160,7 @@ const editMaintenanceWindow = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "editMaintenanceWindow"));
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
createMaintenanceWindows,
|
||||
getMaintenanceWindowById,
|
||||
getMaintenanceWindowsByTeamId,
|
||||
getMaintenanceWindowsByMonitorId,
|
||||
deleteMaintenanceWindow,
|
||||
editMaintenanceWindow,
|
||||
};
|
||||
export default MaintenanceWindowController;
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
getCertificateParamValidation,
|
||||
} from "../validation/joi.js";
|
||||
import sslChecker from "ssl-checker";
|
||||
import { errorMessages, successMessages } from "../utils/messages.js";
|
||||
import { successMessages } from "../utils/messages.js";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { getTokenFromHeaders } from "../utils/utils.js";
|
||||
import logger from "../utils/logger.js";
|
||||
@@ -23,7 +23,14 @@ import axios from "axios";
|
||||
|
||||
const SERVICE_NAME = "monitorController";
|
||||
|
||||
/**
|
||||
class MonitorController {
|
||||
constructor(db, settingsService, jobQueue) {
|
||||
this.db = db;
|
||||
this.settingsService = settingsService;
|
||||
this.jobQueue = jobQueue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all monitors
|
||||
* @async
|
||||
* @param {Express.Request} req
|
||||
@@ -32,9 +39,9 @@ const SERVICE_NAME = "monitorController";
|
||||
* @returns {Promise<Express.Response>}
|
||||
* @throws {Error}
|
||||
*/
|
||||
const getAllMonitors = async (req, res, next) => {
|
||||
getAllMonitors = async (req, res, next) => {
|
||||
try {
|
||||
const monitors = await req.db.getAllMonitors();
|
||||
const monitors = await this.db.getAllMonitors();
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.MONITOR_GET_ALL,
|
||||
@@ -43,9 +50,9 @@ const getAllMonitors = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getAllMonitors"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Returns all monitors with uptime stats for 1,7,30, and 90 days
|
||||
* @async
|
||||
* @param {Express.Request} req
|
||||
@@ -54,9 +61,9 @@ const getAllMonitors = async (req, res, next) => {
|
||||
* @returns {Promise<Express.Response>}
|
||||
* @throws {Error}
|
||||
*/
|
||||
const getAllMonitorsWithUptimeStats = async (req, res, next) => {
|
||||
getAllMonitorsWithUptimeStats = async (req, res, next) => {
|
||||
try {
|
||||
const monitors = await req.db.getAllMonitorsWithUptimeStats();
|
||||
const monitors = await this.db.getAllMonitorsWithUptimeStats();
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.MONITOR_GET_ALL,
|
||||
@@ -65,9 +72,9 @@ const getAllMonitorsWithUptimeStats = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getAllMonitorsWithUptimeStats"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Returns monitor stats for monitor with matching ID
|
||||
* @async
|
||||
* @param {Express.Request} req
|
||||
@@ -76,7 +83,7 @@ const getAllMonitorsWithUptimeStats = async (req, res, next) => {
|
||||
* @returns {Promise<Express.Response>}
|
||||
* @throws {Error}
|
||||
*/
|
||||
const getMonitorStatsById = async (req, res, next) => {
|
||||
getMonitorStatsById = async (req, res, next) => {
|
||||
try {
|
||||
await getMonitorStatsByIdParamValidation.validateAsync(req.params);
|
||||
await getMonitorStatsByIdQueryValidation.validateAsync(req.query);
|
||||
@@ -86,7 +93,7 @@ const getMonitorStatsById = async (req, res, next) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const monitorStats = await req.db.getMonitorStatsById(req);
|
||||
const monitorStats = await this.db.getMonitorStatsById(req);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.MONITOR_STATS_BY_ID,
|
||||
@@ -95,9 +102,9 @@ const getMonitorStatsById = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMonitorStatsById"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) => {
|
||||
getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) => {
|
||||
try {
|
||||
await getCertificateParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
@@ -106,7 +113,7 @@ const getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) =>
|
||||
|
||||
try {
|
||||
const { monitorId } = req.params;
|
||||
const monitor = await req.db.getMonitorById(monitorId);
|
||||
const monitor = await this.db.getMonitorById(monitorId);
|
||||
const certificate = await fetchMonitorCertificate(sslChecker, monitor);
|
||||
|
||||
return res.status(200).json({
|
||||
@@ -119,9 +126,9 @@ const getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) =>
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMonitorCertificate"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Retrieves a monitor by its ID.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -132,7 +139,7 @@ const getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) =>
|
||||
* @returns {Object} The response object with a success status, a message, and the retrieved monitor data.
|
||||
* @throws {Error} If there is an error during the process, especially if the monitor is not found (404) or if there is a validation error (422).
|
||||
*/
|
||||
const getMonitorById = async (req, res, next) => {
|
||||
getMonitorById = async (req, res, next) => {
|
||||
try {
|
||||
await getMonitorByIdParamValidation.validateAsync(req.params);
|
||||
await getMonitorByIdQueryValidation.validateAsync(req.query);
|
||||
@@ -142,7 +149,7 @@ const getMonitorById = async (req, res, next) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const monitor = await req.db.getMonitorById(req.params.monitorId);
|
||||
const monitor = await this.db.getMonitorById(req.params.monitorId);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.MONITOR_GET_BY_ID,
|
||||
@@ -151,9 +158,9 @@ const getMonitorById = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMonitorById"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Retrieves all monitors and a summary for a team based on the team ID.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -166,7 +173,7 @@ const getMonitorById = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status, a message, and the data containing the monitors and summary for the team.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
|
||||
getMonitorsAndSummaryByTeamId = async (req, res, next) => {
|
||||
try {
|
||||
await getMonitorsAndSummaryByTeamIdParamValidation.validateAsync(req.params);
|
||||
await getMonitorsAndSummaryByTeamIdQueryValidation.validateAsync(req.query);
|
||||
@@ -178,7 +185,7 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
|
||||
try {
|
||||
const { teamId } = req.params;
|
||||
const { type } = req.query;
|
||||
const monitorsSummary = await req.db.getMonitorsAndSummaryByTeamId(teamId, type);
|
||||
const monitorsSummary = await this.db.getMonitorsAndSummaryByTeamId(teamId, type);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.MONITOR_GET_BY_USER_ID(teamId),
|
||||
@@ -187,9 +194,9 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getMonitorsAndSummaryByTeamId"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Retrieves all monitors associated with a team by the team's ID.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -201,7 +208,7 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status, a message, and the data containing the monitors for the team.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
const getMonitorsByTeamId = async (req, res, next) => {
|
||||
getMonitorsByTeamId = async (req, res, next) => {
|
||||
try {
|
||||
await getMonitorsByTeamIdValidation.validateAsync(req.params);
|
||||
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
|
||||
@@ -212,7 +219,7 @@ const getMonitorsByTeamId = async (req, res, next) => {
|
||||
|
||||
try {
|
||||
const teamId = req.params.teamId;
|
||||
const monitors = await req.db.getMonitorsByTeamId(req, res);
|
||||
const monitors = await this.db.getMonitorsByTeamId(req, res);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.MONITOR_GET_BY_USER_ID(teamId),
|
||||
@@ -222,9 +229,9 @@ const getMonitorsByTeamId = async (req, res, next) => {
|
||||
next(handleError(error, SERVICE_NAME, "getMonitorsByTeamId"));
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Creates a new monitor and adds it to the job queue.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -235,7 +242,7 @@ const getMonitorsByTeamId = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status, a message indicating the creation of the monitor, and the created monitor data.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
const createMonitor = async (req, res, next) => {
|
||||
createMonitor = async (req, res, next) => {
|
||||
try {
|
||||
await createMonitorBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
@@ -245,20 +252,20 @@ const createMonitor = async (req, res, next) => {
|
||||
|
||||
try {
|
||||
const notifications = req.body.notifications;
|
||||
const monitor = await req.db.createMonitor(req, res);
|
||||
const monitor = await this.db.createMonitor(req, res);
|
||||
|
||||
if (notifications && notifications.length > 0) {
|
||||
monitor.notifications = await Promise.all(
|
||||
notifications.map(async (notification) => {
|
||||
notification.monitorId = monitor._id;
|
||||
return await req.db.createNotification(notification);
|
||||
return await this.db.createNotification(notification);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
await monitor.save();
|
||||
// Add monitor to job queue
|
||||
req.jobQueue.addJob(monitor._id, monitor);
|
||||
this.jobQueue.addJob(monitor._id, monitor);
|
||||
return res.status(201).json({
|
||||
success: true,
|
||||
msg: successMessages.MONITOR_CREATE,
|
||||
@@ -267,9 +274,9 @@ const createMonitor = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "createMonitor"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Checks if the endpoint can be resolved
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -279,7 +286,7 @@ const createMonitor = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status, a message, and the resolution result.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
const checkEndpointResolution = async (req, res, next) => {
|
||||
checkEndpointResolution = async (req, res, next) => {
|
||||
try {
|
||||
await getMonitorURLByQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
@@ -303,9 +310,9 @@ const checkEndpointResolution = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "checkEndpointResolution"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Deletes a monitor by its ID and also deletes associated checks, alerts, and notifications.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -316,7 +323,7 @@ const checkEndpointResolution = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status and a message indicating the deletion of the monitor.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or an error in deleting associated records.
|
||||
*/
|
||||
const deleteMonitor = async (req, res, next) => {
|
||||
deleteMonitor = async (req, res, next) => {
|
||||
try {
|
||||
await getMonitorByIdParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
@@ -325,14 +332,14 @@ const deleteMonitor = async (req, res, next) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const monitor = await req.db.deleteMonitor(req, res, next);
|
||||
const monitor = await this.db.deleteMonitor(req, res, next);
|
||||
// Delete associated checks,alerts,and notifications
|
||||
try {
|
||||
await req.jobQueue.deleteJob(monitor);
|
||||
await req.db.deleteChecks(monitor._id);
|
||||
await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
|
||||
await req.db.deleteNotificationsByMonitorId(monitor._id);
|
||||
await req.db.deleteHardwareChecksByMonitorId(monitor._id);
|
||||
await this.jobQueue.deleteJob(monitor);
|
||||
await this.db.deleteChecks(monitor._id);
|
||||
await this.db.deletePageSpeedChecksByMonitorId(monitor._id);
|
||||
await this.db.deleteNotificationsByMonitorId(monitor._id);
|
||||
await this.db.deleteHardwareChecksByMonitorId(monitor._id);
|
||||
} catch (error) {
|
||||
logger.error({
|
||||
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
|
||||
@@ -345,9 +352,9 @@ const deleteMonitor = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteMonitor"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Deletes all monitors associated with a team.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -358,19 +365,19 @@ const deleteMonitor = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status and a message indicating the number of deleted monitors.
|
||||
* @throws {Error} If there is an error during the deletion process.
|
||||
*/
|
||||
const deleteAllMonitors = async (req, res, next) => {
|
||||
deleteAllMonitors = async (req, res, next) => {
|
||||
try {
|
||||
const token = getTokenFromHeaders(req.headers);
|
||||
const { jwtSecret } = req.settingsService.getSettings();
|
||||
const { jwtSecret } = this.settingsService.getSettings();
|
||||
const { teamId } = jwt.verify(token, jwtSecret);
|
||||
const { monitors, deletedCount } = await req.db.deleteAllMonitors(teamId);
|
||||
const { monitors, deletedCount } = await this.db.deleteAllMonitors(teamId);
|
||||
await Promise.all(
|
||||
monitors.map(async (monitor) => {
|
||||
try {
|
||||
await req.jobQueue.deleteJob(monitor);
|
||||
await req.db.deleteChecks(monitor._id);
|
||||
await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
|
||||
await req.db.deleteNotificationsByMonitorId(monitor._id);
|
||||
await this.jobQueue.deleteJob(monitor);
|
||||
await this.db.deleteChecks(monitor._id);
|
||||
await this.db.deletePageSpeedChecksByMonitorId(monitor._id);
|
||||
await this.db.deleteNotificationsByMonitorId(monitor._id);
|
||||
} catch (error) {
|
||||
logger.error({
|
||||
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
|
||||
@@ -387,9 +394,9 @@ const deleteAllMonitors = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "deleteAllMonitors"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Edits a monitor by its ID, updates its notifications, and updates its job in the job queue.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -402,7 +409,7 @@ const deleteAllMonitors = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status, a message indicating the editing of the monitor, and the edited monitor data.
|
||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||
*/
|
||||
const editMonitor = async (req, res, next) => {
|
||||
editMonitor = async (req, res, next) => {
|
||||
try {
|
||||
await getMonitorByIdParamValidation.validateAsync(req.params);
|
||||
await editMonitorBodyValidation.validateAsync(req.body);
|
||||
@@ -413,27 +420,27 @@ const editMonitor = async (req, res, next) => {
|
||||
|
||||
try {
|
||||
const { monitorId } = req.params;
|
||||
const monitorBeforeEdit = await req.db.getMonitorById(monitorId);
|
||||
const monitorBeforeEdit = await this.db.getMonitorById(monitorId);
|
||||
|
||||
// Get notifications from the request body
|
||||
const notifications = req.body.notifications;
|
||||
|
||||
const editedMonitor = await req.db.editMonitor(monitorId, req.body);
|
||||
const editedMonitor = await this.db.editMonitor(monitorId, req.body);
|
||||
|
||||
await req.db.deleteNotificationsByMonitorId(editedMonitor._id);
|
||||
await this.db.deleteNotificationsByMonitorId(editedMonitor._id);
|
||||
|
||||
await Promise.all(
|
||||
notifications &&
|
||||
notifications.map(async (notification) => {
|
||||
notification.monitorId = editedMonitor._id;
|
||||
await req.db.createNotification(notification);
|
||||
await this.db.createNotification(notification);
|
||||
})
|
||||
);
|
||||
|
||||
// Delete the old job(editedMonitor has the same ID as the old monitor)
|
||||
await req.jobQueue.deleteJob(monitorBeforeEdit);
|
||||
await this.jobQueue.deleteJob(monitorBeforeEdit);
|
||||
// Add the new job back to the queue
|
||||
await req.jobQueue.addJob(editedMonitor._id, editedMonitor);
|
||||
await this.jobQueue.addJob(editedMonitor._id, editedMonitor);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.MONITOR_EDIT,
|
||||
@@ -442,9 +449,9 @@ const editMonitor = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "editMonitor"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Pauses or resumes a monitor based on its current state.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -455,7 +462,7 @@ const editMonitor = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status, a message indicating the new state of the monitor, and the updated monitor data.
|
||||
* @throws {Error} If there is an error during the process.
|
||||
*/
|
||||
const pauseMonitor = async (req, res, next) => {
|
||||
pauseMonitor = async (req, res, next) => {
|
||||
try {
|
||||
await pauseMonitorParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
@@ -463,10 +470,10 @@ const pauseMonitor = async (req, res, next) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const monitor = await req.db.getMonitorById(req.params.monitorId);
|
||||
const monitor = await this.db.getMonitorById(req.params.monitorId);
|
||||
monitor.isActive === true
|
||||
? await req.jobQueue.deleteJob(monitor)
|
||||
: await req.jobQueue.addJob(monitor._id, monitor);
|
||||
? await this.jobQueue.deleteJob(monitor)
|
||||
: await this.jobQueue.addJob(monitor._id, monitor);
|
||||
|
||||
monitor.isActive = !monitor.isActive;
|
||||
monitor.status = undefined;
|
||||
@@ -481,9 +488,9 @@ const pauseMonitor = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "pauseMonitor"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
/**
|
||||
* Adds demo monitors for a team.
|
||||
* @async
|
||||
* @param {Object} req - The Express request object.
|
||||
@@ -494,14 +501,14 @@ const pauseMonitor = async (req, res, next) => {
|
||||
* @returns {Object} The response object with a success status, a message indicating the addition of demo monitors, and the number of demo monitors added.
|
||||
* @throws {Error} If there is an error during the process.
|
||||
*/
|
||||
const addDemoMonitors = async (req, res, next) => {
|
||||
addDemoMonitors = async (req, res, next) => {
|
||||
try {
|
||||
const token = getTokenFromHeaders(req.headers);
|
||||
const { jwtSecret } = req.settingsService.getSettings();
|
||||
const { jwtSecret } = this.settingsService.getSettings();
|
||||
const { _id, teamId } = jwt.verify(token, jwtSecret);
|
||||
const demoMonitors = await req.db.addDemoMonitors(_id, teamId);
|
||||
const demoMonitors = await this.db.addDemoMonitors(_id, teamId);
|
||||
await Promise.all(
|
||||
demoMonitors.map((monitor) => req.jobQueue.addJob(monitor._id, monitor))
|
||||
demoMonitors.map((monitor) => this.jobQueue.addJob(monitor._id, monitor))
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
@@ -512,21 +519,7 @@ const addDemoMonitors = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "addDemoMonitors"));
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
getAllMonitors,
|
||||
getAllMonitorsWithUptimeStats,
|
||||
getMonitorStatsById,
|
||||
getMonitorCertificate,
|
||||
getMonitorById,
|
||||
getMonitorsAndSummaryByTeamId,
|
||||
getMonitorsByTeamId,
|
||||
createMonitor,
|
||||
checkEndpointResolution,
|
||||
deleteMonitor,
|
||||
deleteAllMonitors,
|
||||
editMonitor,
|
||||
pauseMonitor,
|
||||
addDemoMonitors,
|
||||
};
|
||||
export default MonitorController;
|
||||
@@ -1,11 +1,16 @@
|
||||
import { handleError } from "./controllerUtils.js";
|
||||
import { errorMessages, successMessages } from "../utils/messages.js";
|
||||
import { successMessages } from "../utils/messages.js";
|
||||
|
||||
const SERVICE_NAME = "JobQueueController";
|
||||
|
||||
const getMetrics = async (req, res, next) => {
|
||||
class JobQueueController {
|
||||
constructor(jobQueue) {
|
||||
this.jobQueue = jobQueue;
|
||||
}
|
||||
|
||||
getMetrics = async (req, res, next) => {
|
||||
try {
|
||||
const metrics = await req.jobQueue.getMetrics();
|
||||
const metrics = await this.jobQueue.getMetrics();
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.QUEUE_GET_METRICS,
|
||||
@@ -15,11 +20,11 @@ const getMetrics = async (req, res, next) => {
|
||||
next(handleError(error, SERVICE_NAME, "getMetrics"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const getJobs = async (req, res, next) => {
|
||||
getJobs = async (req, res, next) => {
|
||||
try {
|
||||
const jobs = await req.jobQueue.getJobStats();
|
||||
const jobs = await this.jobQueue.getJobStats();
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.QUEUE_GET_METRICS,
|
||||
@@ -29,11 +34,11 @@ const getJobs = async (req, res, next) => {
|
||||
next(handleError(error, SERVICE_NAME, "getJobs"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const addJob = async (req, res, next) => {
|
||||
addJob = async (req, res, next) => {
|
||||
try {
|
||||
await req.jobQueue.addJob(Math.random().toString(36).substring(7));
|
||||
await this.jobQueue.addJob(Math.random().toString(36).substring(7));
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.QUEUE_ADD_JOB,
|
||||
@@ -42,16 +47,18 @@ const addJob = async (req, res, next) => {
|
||||
next(handleError(error, SERVICE_NAME, "addJob"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const obliterateQueue = async (req, res, next) => {
|
||||
obliterateQueue = async (req, res, next) => {
|
||||
try {
|
||||
await req.jobQueue.obliterate();
|
||||
return res.status(200).json({ success: true, msg: successMessages.QUEUE_OBLITERATE });
|
||||
await this.jobQueue.obliterate();
|
||||
return res
|
||||
.status(200)
|
||||
.json({ success: true, msg: successMessages.QUEUE_OBLITERATE });
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "obliterateQueue"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
export { getMetrics, getJobs, addJob, obliterateQueue };
|
||||
};
|
||||
}
|
||||
export default JobQueueController;
|
||||
@@ -3,9 +3,15 @@ import { updateAppSettingsBodyValidation } from "../validation/joi.js";
|
||||
import { handleValidationError, handleError } from "./controllerUtils.js";
|
||||
const SERVICE_NAME = "SettingsController";
|
||||
|
||||
const getAppSettings = async (req, res, next) => {
|
||||
class SettingsController {
|
||||
constructor(db, settingsService) {
|
||||
this.db = db;
|
||||
this.settingsService = settingsService;
|
||||
}
|
||||
|
||||
getAppSettings = async (req, res, next) => {
|
||||
try {
|
||||
const settings = { ...(await req.settingsService.getSettings()) };
|
||||
const settings = { ...(await this.settingsService.getSettings()) };
|
||||
delete settings.jwtSecret;
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
@@ -15,9 +21,9 @@ const getAppSettings = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getAppSettings"));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const updateAppSettings = async (req, res, next) => {
|
||||
updateAppSettings = async (req, res, next) => {
|
||||
try {
|
||||
await updateAppSettingsBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
@@ -26,8 +32,8 @@ const updateAppSettings = async (req, res, next) => {
|
||||
}
|
||||
|
||||
try {
|
||||
await req.db.updateAppSettings(req.body);
|
||||
const updatedSettings = { ...(await req.settingsService.reloadSettings()) };
|
||||
await this.db.updateAppSettings(req.body);
|
||||
const updatedSettings = { ...(await this.settingsService.reloadSettings()) };
|
||||
delete updatedSettings.jwtSecret;
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
@@ -37,6 +43,7 @@ const updateAppSettings = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "updateAppSettings"));
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export { getAppSettings, updateAppSettings };
|
||||
export default SettingsController;
|
||||
@@ -7,7 +7,12 @@ import { successMessages } from "../utils/messages.js";
|
||||
|
||||
const SERVICE_NAME = "statusPageController";
|
||||
|
||||
const createStatusPage = async (req, res, next) => {
|
||||
class StatusPageController {
|
||||
constructor(db) {
|
||||
this.db = db;
|
||||
}
|
||||
|
||||
createStatusPage = async (req, res, next) => {
|
||||
try {
|
||||
await createStatusPageBodyValidation.validateAsync(req.body);
|
||||
} catch (error) {
|
||||
@@ -16,7 +21,7 @@ const createStatusPage = async (req, res, next) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const statusPage = await req.db.createStatusPage(req.body);
|
||||
const statusPage = await this.db.createStatusPage(req.body);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.STATUS_PAGE_CREATE,
|
||||
@@ -25,9 +30,8 @@ const createStatusPage = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "createStatusPage"));
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusPageByUrl = async (req, res, next) => {
|
||||
};
|
||||
getStatusPageByUrl = async (req, res, next) => {
|
||||
try {
|
||||
await getStatusPageParamValidation.validateAsync(req.params);
|
||||
} catch (error) {
|
||||
@@ -37,7 +41,7 @@ const getStatusPageByUrl = async (req, res, next) => {
|
||||
|
||||
try {
|
||||
const { url } = req.params;
|
||||
const statusPage = await req.db.getStatusPageByUrl(url);
|
||||
const statusPage = await this.db.getStatusPageByUrl(url);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: successMessages.STATUS_PAGE_BY_URL,
|
||||
@@ -46,6 +50,7 @@ const getStatusPageByUrl = async (req, res, next) => {
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "getStatusPage"));
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export { createStatusPage, getStatusPageByUrl };
|
||||
export default StatusPageController;
|
||||
Reference in new issue
Block a user