Progress with reviews

This commit is contained in:
oitsjustjose 2022-04-18 15:34:02 -05:00
commit 013202546b
8 changed files with 260 additions and 394 deletions

View file

@ -11,12 +11,20 @@ export default async (req: Request, res: Response) => {
}
const product = await Products.findById(req.params.id);
if (!product) {
return res
.status(404)
.json({ error: `No product with ID ${req.params.id} was found.` });
}
return !!product
? res.status(200).json(product)
: res
.status(404)
.json({ error: `No product with ID ${req.params.id} was found.` });
return res.status(200).json({
...product.toJSON(),
overallRating: product.reviews.length
? product.reviews
.map((x) => x.rating)
.reduce((prev, curr) => prev + curr) / product.reviews.length
: null,
});
} catch (ex) {
LOGGER.error(ex);
return res.status(500).json({ error: ex });

View file

@ -5,7 +5,15 @@ import { LOGGER } from "../../../util/Logger";
export default async (req: Request, res: Response) => {
try {
const products = await Products.find(req.body.searchParams || {});
return res.status(200).send(products);
return res.status(200).json(
products.map((p) => ({
...p.toJSON(),
overallRating: p.reviews.length
? p.reviews.map((x) => x.rating).reduce((prev, curr) => prev + curr) /
p.reviews.length
: null,
}))
);
} catch (ex) {
LOGGER.error(ex);
return res.status(500).json({ error: ex });

View file

@ -21,6 +21,21 @@ export default async (req: Request, res: Response) => {
.json({ error: `Product with id ${req.params.id} could not be located` });
}
const reviewsFromUser = product.reviews.filter((x) =>
x.user._id.equals(req.user._id)
).length;
if (!!reviewsFromUser) {
return res
.status(422)
.json({ error: "You've already left a review for this product" });
}
if (req.body.rating < 0 || req.body.rating > 5.0) {
return res
.status(422)
.json({ error: "Ratings must be between 0.0 and 5.0" });
}
product.reviews = [
...product.reviews,
{

View file

@ -37,6 +37,12 @@ export default async (req: Request, res: Response) => {
return res.status(403).json({ error: "Review isn't yours" });
}
if (req.body.rating < 0 || req.body.rating > 5.0) {
return res
.status(422)
.json({ error: "Ratings must be between 0.0 and 5.0" });
}
rev.rating = req.body.rating || rev.rating;
rev.review.title = req.body.review?.title || rev.review.title;
rev.review.body = req.body.review?.body || rev.review.body;