Progress with reviews
This commit is contained in:
parent
7ad02ccfe2
commit
013202546b
8 changed files with 260 additions and 394 deletions
|
|
@ -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 });
|
||||
|
|
|
|||
|
|
@ -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 });
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
Loading…
Reference in a new issue