| const ProductModel = require('../models/productModel'); |
|
|
| exports.getProducts = async (req, res, next) => { |
| try { |
| let query = {}; |
| |
| if (req.query.keyword) { |
| query.name = { |
| $regex: req.query.keyword, |
| $options: 'i' |
| }; |
| } |
| |
| if (req.query.category) { |
| query.category = req.query.category; |
| } |
| |
| if (req.query.trending === 'true') { |
| query.ratings = { $gte: 4.0 }; |
| } |
| |
| if (req.query.minPrice || req.query.maxPrice) { |
| query.price = {}; |
| if (req.query.minPrice) query.price.$gte = parseFloat(req.query.minPrice); |
| if (req.query.maxPrice) query.price.$lte = parseFloat(req.query.maxPrice); |
| } |
| |
| const products = await ProductModel.find(query); |
| res.json({ |
| success: true, |
| products |
| }); |
| } catch (error) { |
| res.status(500).json({ |
| success: false, |
| message: 'Unable to get products', |
| error: error.message |
| }); |
| } |
| } |
|
|
| exports.getSingleProduct = async (req, res, next) => { |
| try { |
| const product = await ProductModel.findById(req.params.id); |
| res.json({ |
| success: true, |
| product |
| }) |
| } catch (error) { |
| res.status(404).json({ |
| success: false, |
| message: 'Unable to get Product with that ID' |
| }) |
| } |
| } |
|
|
| exports.getRecommendedProducts = async (req, res, next) => { |
| try { |
| const products = await ProductModel.aggregate([ |
| { $sample: { size: 8 } } |
| ]); |
| res.json({ |
| success: true, |
| products |
| }) |
| } catch (error) { |
| res.status(500).json({ |
| success: false, |
| message: 'Unable to get recommended products' |
| }) |
| } |
| } |
|
|
| exports.getRelatedProducts = async (req, res, next) => { |
| try { |
| const { productId } = req.params; |
| const product = await ProductModel.findById(productId); |
| |
| if (!product) { |
| return res.status(404).json({ |
| success: false, |
| message: 'Product not found' |
| }); |
| } |
| |
| const relatedProducts = await ProductModel.find({ |
| category: product.category, |
| _id: { $ne: productId } |
| }).limit(4); |
| |
| res.json({ |
| success: true, |
| products: relatedProducts |
| }) |
| } catch (error) { |
| res.status(500).json({ |
| success: false, |
| message: 'Unable to get related products' |
| }) |
| } |
| } |