Skip to content

Commit e44cd46

Browse files
authored
Merge pull request #38 from shiv7shukla/sorting-for-products-api
Sorting for products api
2 parents ecc168e + 417936f commit e44cd46

2 files changed

Lines changed: 23 additions & 2 deletions

File tree

src/controllers/product.controller.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,4 +122,22 @@ const getProductById = async (req, res, next) => {
122122
return res.json(product);
123123
}
124124

125-
export {getAllProducts, getProductById}
125+
const getProductBySortCategory = async (req, res, next) => {
126+
const sort = req.params.sort;
127+
const sortOptions = {
128+
best_selling: { sale: -1 }, // Default
129+
a_z: { name: 1 },
130+
z_a: { name: -1 },
131+
price_asc: { price: 1 },
132+
price_desc: { price: -1 },
133+
rating_asc: { rating: 1 },
134+
rating_desc: { rating: -1 },
135+
};
136+
sort=typeof sort=="string" && sortOptions[sort]?sortOptions[sort]:sortOptions['best_selling'];
137+
const products=(await Product.find()).sort(sort);
138+
if(!products)
139+
return next(new HttpException(404, "No products found"));
140+
return res.json(products);
141+
}
142+
143+
export {getAllProducts, getProductById, getProductBySortCategory};

src/routes/product.routes.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import express from 'express';
2-
import { getAllProducts, getProductById } from '../controllers/product.controller.js';
2+
import { getAllProducts, getProductById, getProductBySortCategory } from '../controllers/product.controller.js';
33

44
const router = express.Router();
55

@@ -9,4 +9,7 @@ router.get('/', getAllProducts);
99
// Fetch product by ID
1010
router.get('/:id',getProductById);
1111

12+
//Fetch product accoridng to sort category
13+
router.get('/:sort', getProductBySortCategory);
14+
1215
export default router

0 commit comments

Comments
 (0)