Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/controllers/product.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,22 @@ const getProductById = async (req, res, next) => {
return res.json(product);
}

export {getAllProducts, getProductById}
const getProductBySortCategory = async (req, res, next) => {
const sort = 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};
5 changes: 4 additions & 1 deletion src/routes/product.routes.js
Original file line number Diff line number Diff line change
@@ -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();

Expand All @@ -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