From 9f56371ff9fb227011ef02398d5b3e9fe6d37b4f Mon Sep 17 00:00:00 2001 From: syedmujahidahmed Date: Fri, 29 Mar 2024 17:19:56 +0530 Subject: [PATCH] added getAllProducts api --- resources/Products/ProductController.js | 42 +++++++++++++++++++++++++ resources/Products/ProductRoute.js | 2 ++ 2 files changed, 44 insertions(+) diff --git a/resources/Products/ProductController.js b/resources/Products/ProductController.js index d1de412..9fb4748 100644 --- a/resources/Products/ProductController.js +++ b/resources/Products/ProductController.js @@ -75,6 +75,48 @@ export const getAllProduct = async (req, res) => { }); } }; +// get all product with device products first +export const getAllProductsDevicesFirst = async (req, res) => { + try { + // we want products with category name Device to be displayed first, so i have first found the products with category name Devices then made another request to find all products and filtered products with category devices , then merged both arrays so we get devices first then all other categories + + const categoryName = 'Devices'; + // Find the category object by name first + const category = await CategoryModel.findOne({ categoryName }); + + if (!category) { + throw new Error("Category not found"); + } + // products with device category + const deviceProducts = await Product.find({ category: category._id }).populate('category'); + + // all products + const allProducts = await Product.find() + .populate({ + path: "category gst addedBy", + select: "name categoryName tax", + }) + .sort({ + createdAt: -1, + }); + // filtering out products with device category + const filteredProducts = allProducts.filter((ele) => { return ele.category?.categoryName !== categoryName }) + + // merging both deviceProcuts and filtered products + const product = deviceProducts.concat(filteredProducts) + if (product) { + return res.status(200).json({ + success: true, + product, + }); + } + } catch (error) { + res.status(500).json({ + success: false, + msg: error.message ? error.message : "Something went wrong!", + }); + } +}; //get One Product export const getOneProduct = async (req, res) => { try { diff --git a/resources/Products/ProductRoute.js b/resources/Products/ProductRoute.js index 220f4e3..2159d1f 100644 --- a/resources/Products/ProductRoute.js +++ b/resources/Products/ProductRoute.js @@ -7,6 +7,7 @@ import { getOneProduct, deleteImageFromCloudinary, getProductsByCategory, + getAllProductsDevicesFirst, } from "./ProductController.js"; const router = express.Router(); import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; @@ -14,6 +15,7 @@ router .route("/product/create/") .post(isAuthenticatedUser, authorizeRoles("admin"), createProduct); router.route("/product/getAll/").get(getAllProduct); +router.route("/product/getAllProductsDevicesFrist/").get(getAllProductsDevicesFirst); router.route("/product/getOne/:id").get(getOneProduct); router .route("/product/update/:id")