From 428df6f30c84de636abb63f2205af6166e932720 Mon Sep 17 00:00:00 2001 From: print-signs Date: Fri, 20 Oct 2023 11:27:52 +0530 Subject: [PATCH] Product page Done --- package-lock.json | 13 +++ package.json | 1 + resources/Category/categoryController.js | 10 +- resources/Products/ProductController.js | 135 +++++++++++++++-------- resources/Products/ProductModel.js | 4 + resources/Products/ProductRoute.js | 42 ++++--- 6 files changed, 134 insertions(+), 71 deletions(-) diff --git a/package-lock.json b/package-lock.json index 49dd341..a884a6e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -26,6 +26,7 @@ "nodemailer": "^6.9.4", "nodemon": "^3.0.1", "secure-random-password": "^0.2.3", + "uuid": "^9.0.1", "validator": "^13.7.0" } }, @@ -2283,6 +2284,18 @@ "node": ">= 0.4.0" } }, + "node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "bin": { + "uuid": "dist/bin/uuid" + } + }, "node_modules/validator": { "version": "13.7.0", "resolved": "https://registry.npmjs.org/validator/-/validator-13.7.0.tgz", diff --git a/package.json b/package.json index d35d4f8..be65ee7 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "nodemailer": "^6.9.4", "nodemon": "^3.0.1", "secure-random-password": "^0.2.3", + "uuid": "^9.0.1", "validator": "^13.7.0" } } diff --git a/resources/Category/categoryController.js b/resources/Category/categoryController.js index 27d8443..82d991e 100644 --- a/resources/Category/categoryController.js +++ b/resources/Category/categoryController.js @@ -52,7 +52,7 @@ export const updateCategory = async (req, res) => { try { if (!req?.user) return res.status(400).json({ message: "please login !" }); const { _id } = req.params; - console.log(_id); + const { categoryName } = req.body; if (!mongoose.Types.ObjectId.isValid(_id)) { return res.status(404).json({ error: "Can not find the document " }); @@ -90,11 +90,9 @@ export const deleteCategory = async (req, res) => { const deleteCategory = await CategoryModel.findOneAndDelete({ _id: _id }); if (!deleteCategory) { - return res - .status(404) - .json({ - error: "Can not find the document with the provided id to delete ", - }); + return res.status(404).json({ + error: "Can not find the document with the provided id to delete ", + }); } res.status(200).json({ success: true, deleteCategory }); } catch (error) { diff --git a/resources/Products/ProductController.js b/resources/Products/ProductController.js index 5bcc71d..62fabd1 100644 --- a/resources/Products/ProductController.js +++ b/resources/Products/ProductController.js @@ -1,5 +1,6 @@ import { Product } from "./ProductModel.js"; import cloudinary from "../../Utils/cloudinary.js"; +import { v4 as uuidv4 } from "uuid"; export const createProduct = async (req, res) => { try { @@ -34,6 +35,8 @@ export const createProduct = async (req, res) => { req.body.image = imagesLinks; req.body.addedBy = req.user.id; + const newUniquid = uuidv4(); + req.body.uniqueId = newUniquid.replace(/-/g, "").substring(0, 10); const data = await Product.create({ ...req.body }); res.status(201).json({ @@ -42,7 +45,6 @@ export const createProduct = async (req, res) => { msg: " create Product Successfully!!", }); } catch (error) { - // console.log(error) res.status(500).json({ success: false, msg: error.message, @@ -87,42 +89,30 @@ export const getOneProduct = async (req, res) => { // 3.update Product export const updateProduct = async (req, res) => { + const { name, description, price, category, image } = req.body; + try { - // const newProductData = { - // name: req.body.name, - // description: req.body.description, - // price: req.body.base_Price, + // Prepare an array for the images + const jsonArray = JSON.parse(image); + const AllImages = jsonArray.map(({ public_id, url }) => ({ + public_id, + url, + })); - // } - - if (req.files) { - // req.body.addedBy = req.user.id; - // const image_file = req.files.image; - const getProduct = await Product.findById(req.params.id); - - if (getProduct) { - // Deleting Images From Cloudinary - for (let i = 0; i < getProduct.image.length; i++) { - await cloudinary.v2.uploader.destroy(getProduct.image[i].public_id); - } - } - let images = []; - let Allfiles = req.files.image; - if (typeof Allfiles.tempFilePath === "string") { - let filepath = Allfiles.tempFilePath; - - images.push(filepath); - } else { - Allfiles.map((item) => { - images.push(item.tempFilePath); - }); - } + if (req.files && req.files.newImages) { + const newuploadImages = Array.isArray(req.files.newImages) + ? req.files.newImages + : [req.files.newImages]; const imagesLinks = []; - for (let i = 0; i < images.length; i++) { - const result = await cloudinary.v2.uploader.upload(images[i], { - folder: "jatinMor/product", - }); + + for (let i = 0; i < newuploadImages.length; i++) { + const result = await cloudinary.v2.uploader.upload( + newuploadImages[i].tempFilePath, + { + folder: "jatinMor/product", + } + ); imagesLinks.push({ public_id: result.public_id, @@ -130,24 +120,47 @@ export const updateProduct = async (req, res) => { }); } - req.body.image = imagesLinks; + // Combine the existing images and the newly uploaded images + const updatedImages = [...AllImages, ...imagesLinks]; + + // Perform the product update + const ModifyProduct = await Product.findOneAndUpdate( + { _id: req.params.id }, + { + $set: { + name, + description, + price, + category, + image: updatedImages, + }, + }, + { new: true } + ); + return res.status(200).json({ + success: true, + ModifyProduct, + }); + } else { + const ModifyProduct = await Product.findOneAndUpdate( + { _id: req.params.id }, + { + $set: { + name, + description, + price, + category, + image: AllImages, + }, + }, + { new: true } + ); + return res.status(200).json({ + success: true, + ModifyProduct, + }); } - - const ModifyProduct = await Product.findByIdAndUpdate( - req.params.id, - req.body, - - { new: true } - // runValidators: true, - // useFindAndModify: false, - ); - - res.status(200).json({ - success: true, - ModifyProduct, - }); } catch (error) { - // console.log(error) res.status(500).json({ success: false, msg: error.message ? error.message : "Something went wrong!", @@ -155,6 +168,30 @@ export const updateProduct = async (req, res) => { } }; +export const deleteImageFromCloudinary = async (req, res) => { + const { public_id } = req.params; + + try { + if (!public_id) { + return res.status(400).json({ + success: false, + msg: "Please Provide Product ID!", + }); + } + const response = await cloudinary.v2.uploader.destroy(public_id); + if (response) { + res.status(200).json({ + success: true, + msg: "Product Deleted Successfully!!", + }); + } + } catch (error) { + res.status(500).json({ + success: false, + msg: error.message ? error.message : "Something went wrong!", + }); + } +}; //delete one Product export const deleteProduct = async (req, res) => { try { diff --git a/resources/Products/ProductModel.js b/resources/Products/ProductModel.js index 4c50c8a..cf96608 100644 --- a/resources/Products/ProductModel.js +++ b/resources/Products/ProductModel.js @@ -9,6 +9,10 @@ const productSchema = new Schema( required: [true, "Please Enter product Name"], trim: true, }, + uniqueId: { + type: String, + required: true, + }, description: { type: String, maxLength: [100, "description cannot exceed 100 characters"], diff --git a/resources/Products/ProductRoute.js b/resources/Products/ProductRoute.js index 6ec1aea..cb9dc15 100644 --- a/resources/Products/ProductRoute.js +++ b/resources/Products/ProductRoute.js @@ -1,21 +1,31 @@ import express from "express"; import { - createProduct, - getAllProduct, - updateProduct, - deleteProduct, - getOneProduct, - - -} from "./ProductController.js" + createProduct, + getAllProduct, + updateProduct, + deleteProduct, + getOneProduct, + deleteImageFromCloudinary, +} from "./ProductController.js"; const router = express.Router(); -import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js" -router.route("/product/create/").post(isAuthenticatedUser, authorizeRoles("admin"), createProduct) -router.route("/product/getAll/").get(getAllProduct) -router.route("/product/getOne/:id").get(getOneProduct) -router.route("/product/update/:id").put(isAuthenticatedUser, authorizeRoles("admin"), updateProduct); -router.route("/product/delete/:id").delete(isAuthenticatedUser, authorizeRoles("admin"), deleteProduct); +import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; +router + .route("/product/create/") + .post(isAuthenticatedUser, authorizeRoles("admin"), createProduct); +router.route("/product/getAll/").get(getAllProduct); +router.route("/product/getOne/:id").get(getOneProduct); +router + .route("/product/update/:id") + .patch(isAuthenticatedUser, authorizeRoles("admin"), updateProduct); +router + .route("/product/delete/:id") + .delete(isAuthenticatedUser, authorizeRoles("admin"), deleteProduct); +router + .route("/product/deleteImage/jatinMor/product/:public_id") + .delete( + isAuthenticatedUser, + authorizeRoles("admin"), + deleteImageFromCloudinary + ); export default router; - -