Skip to content

Commit

Permalink
fix: prevent createCategory function from adding an existing category
Browse files Browse the repository at this point in the history
Change `$push` operation to `$addToSet` in `createCategory` function for avoiding
duplicating existing categories, And make the function returns `null` if the incoming
category is already exist.

Add "if" statement to `products_createCategory_post` route handler to check if
the respond of `createCategory` function equals `null` for returning an error
with "The category already exist" message.
  • Loading branch information
AbdulrhmanGoni committed Apr 12, 2024
1 parent 0b4113b commit 8d106e4
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
10 changes: 7 additions & 3 deletions src/controllers/admin-controllers/createCategory.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@ import SettingsModel from "../../models/Settings.js";
export default async function createCategory(category, session) {
try {
const respond = await SettingsModel.updateOne(
{},
{ $push: { productsCategories: [category] } },
{ productsCategories: { $nin: [category] } },
{ $addToSet: { productsCategories: [category] } },
{ session }
);
return !!respond.modifiedCount;

if (respond.acknowledged && respond.modifiedCount === 0) {
return null
}
return !!respond.modifiedCount
} catch (error) {
console.log(error)
return;
Expand Down
5 changes: 4 additions & 1 deletion src/routes/admin_routes/products_createCategory_post.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ export default asyncRouteHandler(
const session = await startSession();
session.startTransaction();
const dbUpdateResponse = await AdminController.createCategory(category, session);
if (dbUpdateResponse === null) {
return next(new ErrorGenerator("The category already exist", 400));
}
const cacheUpdateResponse = await updateRedisCache("store-variables", (variablesObject) => {
variablesObject?.productsCategories.push(category)
return variablesObject
Expand All @@ -23,7 +26,7 @@ export default asyncRouteHandler(
res.status(400).json(false);
}
} else {
next(new ErrorGenerator("You didn't provide a valid category name", 400))
next(new ErrorGenerator("Ivalid Category Name", 400));
}
}
)

0 comments on commit 8d106e4

Please sign in to comment.