Skip to content

Commit

Permalink
Update category controller and routes
Browse files Browse the repository at this point in the history
  • Loading branch information
bewake24 committed Nov 17, 2024
1 parent 0a650bd commit 6bd8cd9
Show file tree
Hide file tree
Showing 16 changed files with 91 additions and 33 deletions.
84 changes: 60 additions & 24 deletions controllers/category.controller.js
Original file line number Diff line number Diff line change
@@ -1,58 +1,94 @@
const {
MONGOOSE_DUPLICATE_KEY,
MONGOOSE_VALIDATION_ERROR,
MONGOOSE_CAST_ERROR,
MONGOOSE_OBJECT_ID,
} = require("../constants/models.constants");
const Category = require("../model/category.model");
const Product = require("../model/product.model");
const ApiResponse = require("../utils/ApiResponse");
const asyncHandler = require("../utils/asyncHandler");

const createCategory = asyncHandler(async (req, res) => {
try {
const category = await Category.create(req.body);
ApiResponse.success(res, "Category created successfully", category);
let thumbnail;
console.log(req.file);
if (req.file) {
thumbnail = req.file.filename;
}
const category = await Category.create({ ...req.body, thumbnail });
ApiResponse.success(res, "Category created successfully", category, 201);
} catch (error) {
if (error.name === MONGOOSE_VALIDATION_ERROR) {
return ApiResponse.error(res, invalidFieldMessage(error), 400);
}
if (error.code === MONGOOSE_DUPLICATE_KEY) {
return ApiResponse.error(res, "Category already exists", 400);
}
ApiResponse.error(res, "Error while creating category", 500);
}
});

const getCategories = asyncHandler(async (req, res) => {
try {
const categories = await Category.find();
ApiResponse.success(res, "Categories fetched successfully", categories);

ApiResponse.success(
res,
"Categories fetched successfully",
categories.length ? categories : "No categories found",
200
);
} catch (error) {
ApiResponse.error(res, "Error while fetching categories", 500);
}
});

const deleteCategory = asyncHandler(async (req, res) => {
try {
const category = await Category.find(
{ slug: req.params.slug } || { _id: req.params.id }
console.log(req.params);
const category = await Category.findOne(req.params);

if (!category) {
return ApiResponse.notFound(res, "Category not found", 404);
}

// Use async/await with Promise.all to handle product updates
const products = await Product.find({ categories: category._id });

// Remove the category reference from each product
await Promise.all(
products.map(async (product) => {
product.category = product.category.filter((c) => c !== category._id);
await product.save(); // Make sure each product is saved after updating
})
);

// Can we use pre save hooks to save update products category name instead of doing this here.
Product.find({ categories: category._id }).then((products) => {
products.forEach((product) => {
product.category = [
...product.category.filter((c) => c !== category._id),
];
product.save();
});
});
// Delete the category
await category.deleteOne();

category.delete();
ApiResponse.success(res, "Category deleted successfully", {});
} catch (error) {
ApiResponse.error(res, "Error while deleting category", 500);
if (
error.name === MONGOOSE_CAST_ERROR &&
error.kind === MONGOOSE_OBJECT_ID
) {
return ApiResponse.notFound(res, "Invalid object id provided", 404);
}
ApiResponse.error(res, "Error while deleting category", error, 500);
}
});

const updateCategory = asyncHandler(async (req, res) => {
try {
const { name, slug, thumbnail, isActive } = req.body;
const category = await Category.find(
{ slug: req.params.slug } || { _id: req.params.id },
{
new: true,
}
);
const { name, slug, isActive } = req.body;
let thumbnail;
if (req.file) {
thumbnail = req.file.filename;
}
const category = await Category.find(req.params, {
new: true,
});

if (name) {
// Can we use pre save hooks to save update products category name instead of doing this here.
Expand All @@ -67,7 +103,7 @@ const updateCategory = asyncHandler(async (req, res) => {
}

const updatedCategory = await Category.findOneAndUpdate(
{ slug: req.params.slug } || { _id: req.params.id },
req.params,
{
name,
slug,
Expand Down
10 changes: 3 additions & 7 deletions middleware/multer.middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const { validateUsername } = require("../utils/inputValidation/validators.js");
const storage = multer.diskStorage({
destination: function (req, _, cb) {
const username = req.user?.username || validateUsername(req.body.username);
console.log(req.body);

if (!username) {
// Tell the multer to skip uploading the file
Expand All @@ -16,13 +17,7 @@ const storage = multer.diskStorage({
);
}

const uploadFilePath = path.join(
__dirname,
"..",
"public",
"uploads",
username
);
const uploadFilePath = path.join(__dirname, "..", "public", "uploads");

//Check if Filepath exists or not
if (!fs.existsSync(uploadFilePath)) {
Expand All @@ -33,6 +28,7 @@ const storage = multer.diskStorage({
},
filename: function (_, file, cb) {
const uniqueName = uuidv4() + path.extname(file.originalname);
console.log(file.fieldname);
cb(null, file.fieldname + "-" + uniqueName);
},
});
Expand Down
Binary file modified public/uploads/.DS_Store
Binary file not shown.
Binary file not shown.
Binary file removed public/uploads/bewake26/.DS_Store
Binary file not shown.
Binary file not shown.
Binary file removed public/uploads/butki/.DS_Store
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
30 changes: 28 additions & 2 deletions routes/category.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,40 @@ const router = express.Router();
const upload = require("../middleware/multer.middleware");
const verifyJWT = require("../middleware/verifyJWT.middleware");
const verifyRoles = require("../middleware/verifyRoles.middleware");
const ROLES_LIST = require("../config/rolesList");

router
.route("/")
.route("/create-category")
.post(
verifyJWT,
verifyRoles("admin"),
verifyRoles(ROLES_LIST.ADMIN, ROLES_LIST.MANAGER),
upload.single("thumbnail"),
createCategory
);

router
.route("/get-categories")
.get(
verifyJWT,
verifyRoles(ROLES_LIST.ADMIN, ROLES_LIST.MANAGER),
getCategories
);

router
.route("/delete-category/:slug")
.delete(
verifyJWT,
verifyRoles(ROLES_LIST.ADMIN, ROLES_LIST.MANAGER),
deleteCategory
);

router
.route("/update-category/:slug")
.patch(
verifyJWT,
verifyRoles(ROLES_LIST.ADMIN, ROLES_LIST.MANAGER),
upload.single("thumbnail"),
updateCategory
);

module.exports = router;

0 comments on commit 6bd8cd9

Please sign in to comment.