Initial commit
This commit is contained in:
50
server/controllers/reviewController.js
Normal file
50
server/controllers/reviewController.js
Normal file
@@ -0,0 +1,50 @@
|
||||
const Review = require('../models/Review');
|
||||
const Product = require('../models/Product');
|
||||
const { successResponse, errorResponse } = require('../utils/apiResponse');
|
||||
|
||||
const getProductReviews = async (req, res, next) => {
|
||||
try {
|
||||
const reviews = await Review.find({ product: req.params.productId, isApproved: true })
|
||||
.populate('user', 'name avatar')
|
||||
.sort({ createdAt: -1 });
|
||||
|
||||
return successResponse(res, 'Reviews retrieved', reviews);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
const createReview = async (req, res, next) => {
|
||||
try {
|
||||
const { productId, rating, title, comment } = req.body;
|
||||
|
||||
const existing = await Review.findOne({ user: req.user._id, product: productId });
|
||||
if (existing) {
|
||||
return errorResponse(res, 'You have already reviewed this product', [], 400);
|
||||
}
|
||||
|
||||
const review = await Review.create({
|
||||
user: req.user._id,
|
||||
product: productId,
|
||||
rating: Number(rating),
|
||||
title,
|
||||
comment
|
||||
});
|
||||
|
||||
// Update Product average rating
|
||||
const reviews = await Review.find({ product: productId, isApproved: true });
|
||||
const avgRating = reviews.reduce((acc, item) => item.rating + acc, 0) / reviews.length;
|
||||
|
||||
await Product.findByIdAndUpdate(productId, {
|
||||
rating: Number(avgRating.toFixed(1)),
|
||||
numReviews: reviews.length
|
||||
});
|
||||
|
||||
return successResponse(res, 'Review submitted successfully', review, 201);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { getProductReviews, createReview };
|
||||
|
||||
Reference in New Issue
Block a user