complementary deletions on user delete

This commit is contained in:
MuhammadKhalilzadeh committed 2024-06-28 20:13:07 +03:30
1 parent 318b62cd3b
commit e11ae4d460
3 files changed
+34 -2

No files matched your search

+14 -2
View File
@@ -238,7 +238,7 @@ const resetPasswordController = async (req, res, next) => {
const deleteUserController = async (req, res, next) => {
try {
// Validate user
await editUserParamValidation.validateAsync(req.params);
await editUserParamValidation.userDeleteValidation(req.params.userId);
// Check if the user exists
const user = await req.db.getUserById(req.params.userId);
@@ -246,7 +246,19 @@ const deleteUserController = async (req, res, next) => {
throw new Error(errorMessages.DB_USER_NOT_FOUND);
}
// Delete the user
// Step 1: Find all monitors associated with the user
const monitors = await req.db.getMonitorsByUserId(req.params.userId);
// Step 2: For each monitor, delete all associated checks and alerts
for (const monitor of monitors) {
await req.db.deleteChecks(monitor.id);
await req.db.deleteAlertByMonitorId(monitor.id);
}
// Step 3: Delete all monitors associated with the user
await req.db.deleteMonitorsByUserId(req.params.userId);
// Step 4: Finally, delete the user
await req.db.deleteUser(req.params.userId);
return res.status(200).json({
+16
View File
@@ -303,6 +303,21 @@ const deleteAllMonitors = async (req, res) => {
}
};
/**
* Delete all monitors associated with a user ID
* @async
* @param {string} userId - The ID of the user whose monitors are to be deleted.
* @returns {Promise} A promise that resolves when the operation is complete.
*/
const deleteMonitorsByUserId = async (userId) => {
try {
const result = await Monitor.deleteMany({ userId: userId });
return result;
} catch (error) {
throw error;
}
};
/**
* Edit a monitor by ID
* @async
@@ -539,4 +554,5 @@ module.exports = {
editAlert,
deleteAlert,
deleteAlertByMonitorId,
deleteMonitorsByUserId
};
+4
View File
@@ -43,6 +43,10 @@ const newPasswordValidation = joi.object({
confirm: joi.string(),
});
const userDeleteValidation = joi.object({
userId: joi.string().required(),
});
//****************************************
// Monitors
//****************************************