From 9b3ede4485ef1454c1218937c7d9c0a2220f2a6c Mon Sep 17 00:00:00 2001 From: Shiv Shukla Date: Fri, 10 Oct 2025 19:22:27 +0530 Subject: [PATCH 1/2] feat:implement sorting for products api --- src/controllers/product.controller.js | 20 +++++++++++++++++++- src/routes/product.routes.js | 5 ++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/controllers/product.controller.js b/src/controllers/product.controller.js index 23ad5a6..529791a 100644 --- a/src/controllers/product.controller.js +++ b/src/controllers/product.controller.js @@ -122,4 +122,22 @@ const getProductById = async (req, res, next) => { return res.json(product); } -export {getAllProducts, getProductById} +const getProductBySortCategory = async (req, res, next) => { + const category = req.params.sort; + const sortOptions = { + best_selling: { sale: -1 }, // Default + a_z: { name: 1 }, + z_a: { name: -1 }, + price_asc: { price: 1 }, + price_desc: { price: -1 }, + rating_asc: { rating: 1 }, + rating_desc: { rating: -1 }, + }; + sort=typeof sort=="string" && sortOptions[sort]?sortOptions[sort]:sortOptions['best_selling']; + const products=(await Product.find()).sort(sort); + if(!products) + return next(new HttpException(404, "No products found")); + return res.json(products); +} + +export {getAllProducts, getProductById, getProductBySortCategory}; diff --git a/src/routes/product.routes.js b/src/routes/product.routes.js index a0ca63a..1f61d77 100644 --- a/src/routes/product.routes.js +++ b/src/routes/product.routes.js @@ -1,5 +1,5 @@ import express from 'express'; -import { getAllProducts, getProductById } from '../controllers/product.controller.js'; +import { getAllProducts, getProductById, getProductBySortCategory } from '../controllers/product.controller.js'; const router = express.Router(); @@ -9,4 +9,7 @@ router.get('/', getAllProducts); // Fetch product by ID router.get('/:id',getProductById); +//Fetch product accoridng to sort category +router.get('/:sort', getProductBySortCategory); + export default router \ No newline at end of file From 417936f999b4bd879471525d06f728ce557faa4a Mon Sep 17 00:00:00 2001 From: Shiv Shukla Date: Fri, 10 Oct 2025 19:28:52 +0530 Subject: [PATCH 2/2] linting done --- src/controllers/product.controller.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/controllers/product.controller.js b/src/controllers/product.controller.js index 529791a..6c510f0 100644 --- a/src/controllers/product.controller.js +++ b/src/controllers/product.controller.js @@ -123,7 +123,7 @@ const getProductById = async (req, res, next) => { } const getProductBySortCategory = async (req, res, next) => { - const category = req.params.sort; + const sort = req.params.sort; const sortOptions = { best_selling: { sale: -1 }, // Default a_z: { name: 1 },