Skip to content

Commit

Permalink
Merge pull request #13 from adnan-mujagic/amarell/favoriteProducts
Browse files Browse the repository at this point in the history
Favorite products by average rating
  • Loading branch information
adnan-mujagic authored Jun 23, 2022
2 parents 8a45630 + 674c809 commit 08ee42c
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
61 changes: 61 additions & 0 deletions controllers/adminController.js
Original file line number Diff line number Diff line change
@@ -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) => {
Expand Down Expand Up @@ -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",
});
}
};
3 changes: 3 additions & 0 deletions routes/adminRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const {
isAdmin,
lowestAmountInStock,
mostSold,
getFavoriteProducts,
} = require("../controllers/adminController");

let router = require("express").Router();
Expand All @@ -12,4 +13,6 @@ router.route("/lowInStock").get(lowestAmountInStock);

router.route("/mostSold").get(mostSold);

router.route("/favorites").get(getFavoriteProducts);

module.exports = router;

0 comments on commit 08ee42c

Please sign in to comment.