diff --git a/controllers/adminController.js b/controllers/adminController.js index 4d926f0..bef2b90 100644 --- a/controllers/adminController.js +++ b/controllers/adminController.js @@ -1,5 +1,6 @@ const Order = require("../models/orderModel"); const Product = require("../models/productModel"); +const Review = require("../models/reviewModel"); const { verifyAuthorization } = require("../utilities/verifyAuthorization"); module.exports.isAdmin = (req, res) => { @@ -82,3 +83,63 @@ module.exports.mostSold = async (req, res) => { data: data, }); }; + +module.exports.getFavoriteProducts = async (req, res) => { + if (!verifyAuthorization(req.headers, ["ADMIN"])) { + return res.status(403).json({ + message: "Unauthorized", + }); + } + + const pipeline = [ + { + $group: { + _id: "$product", + average_rating: { + $avg: "$rating", + }, + }, + }, + { + $sort: { + average_rating: -1, + }, + }, + { + $lookup: { + from: "products", + localField: "_id", + foreignField: "_id", + as: "product", + }, + }, + { + $unwind: { + path: "$product", + }, + }, + { + $limit: 5, + }, + { + $project: { + product: 1, + _id: 0, + average_rating: 1, + }, + }, + ]; + + const data = await Review.aggregate(pipeline); + + if (data) { + return res.status(200).json({ + message: "Best rated products fetched successfully", + data, + }); + } else { + return res.status(400).json({ + message: "Something went wrong when fetching best rated products", + }); + } +}; diff --git a/routes/adminRoutes.js b/routes/adminRoutes.js index 162d05a..f4b0846 100644 --- a/routes/adminRoutes.js +++ b/routes/adminRoutes.js @@ -2,6 +2,7 @@ const { isAdmin, lowestAmountInStock, mostSold, + getFavoriteProducts, } = require("../controllers/adminController"); let router = require("express").Router(); @@ -12,4 +13,6 @@ router.route("/lowInStock").get(lowestAmountInStock); router.route("/mostSold").get(mostSold); +router.route("/favorites").get(getFavoriteProducts); + module.exports = router;