added getAllProducts api

This commit is contained in:
syedmujahidahmed 2024-03-29 17:19:56 +05:30
parent 939b3ed996
commit 9f56371ff9
2 changed files with 44 additions and 0 deletions

View File

@ -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 {

View File

@ -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")