get product by category api created
This commit is contained in:
parent
a780e55122
commit
dee0a3a701
@ -54,7 +54,7 @@ export const createProduct = async (req, res) => {
|
||||
//get All Product
|
||||
export const getAllProduct = async (req, res) => {
|
||||
try {
|
||||
const product = await Product.find({ addedBy: req.user._id }).sort({
|
||||
const product = await Product.find().sort({
|
||||
createdAt: -1,
|
||||
});
|
||||
if (product) {
|
||||
@ -232,3 +232,29 @@ export const deleteProduct = async (req, res) => {
|
||||
});
|
||||
}
|
||||
};
|
||||
export const getProductsByCategory = async (req, res) => {
|
||||
const { categoryName } = req.params; // Assuming category name is in the route
|
||||
|
||||
try {
|
||||
const products = await Product.find({
|
||||
category: categoryName,
|
||||
}).sort({ createdAt: -1 });
|
||||
|
||||
if (products && products.length > 0) {
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
products,
|
||||
});
|
||||
} else {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
msg: "No products found for this category",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
msg: error.message ? error.message : "Something went wrong!",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
@ -6,18 +6,15 @@ import {
|
||||
deleteProduct,
|
||||
getOneProduct,
|
||||
deleteImageFromCloudinary,
|
||||
getProductsByCategory,
|
||||
} 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(isAuthenticatedUser, authorizeRoles("admin"), getAllProduct);
|
||||
router
|
||||
.route("/product/getOne/:id")
|
||||
.get(isAuthenticatedUser, authorizeRoles("admin"), getOneProduct);
|
||||
router.route("/product/getAll/").get(getAllProduct);
|
||||
router.route("/product/getOne/:id").get(getOneProduct);
|
||||
router
|
||||
.route("/product/update/:id")
|
||||
.patch(isAuthenticatedUser, authorizeRoles("admin"), updateProduct);
|
||||
@ -31,5 +28,5 @@ router
|
||||
authorizeRoles("admin"),
|
||||
deleteImageFromCloudinary
|
||||
);
|
||||
|
||||
router.route("/products/category/:categoryName").get(getProductsByCategory);
|
||||
export default router;
|
||||
|
Loading…
Reference in New Issue
Block a user