From 5acb1b7bf0f5519e08fcc787a913d5922168d8c8 Mon Sep 17 00:00:00 2001 From: Ahmed Hisham Date: Tue, 29 Sep 2026 12:27:38 +0300 Subject: [PATCH] Implement book rating API: model, controller, routes, summary aggregation --- server/package-lock.json | 2 + server/src/controllers/ratingController.js | 50 +++++++++++++++++----- server/src/models/Rating.js | 11 ++--- server/src/routes/ratings.js | 7 ++- 4 files changed, 53 insertions(+), 17 deletions(-) diff --git a/server/package-lock.json b/server/package-lock.json index b819a71..0c230a0 100644 --- a/server/package-lock.json +++ b/server/package-lock.json @@ -53,6 +53,7 @@ "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", @@ -1503,6 +1504,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.11.25", "caniuse-lite": "^1.0.30001810", diff --git a/server/src/controllers/ratingController.js b/server/src/controllers/ratingController.js index 1df9ca0..3d16f37 100644 --- a/server/src/controllers/ratingController.js +++ b/server/src/controllers/ratingController.js @@ -1,33 +1,63 @@ +import mongoose from 'mongoose'; import { Rating } from '../models/Rating.js'; // GET /api/ratings -// TODO: implement per README.md section 2. export async function getAllRatings(req, res, next) { try { - // TODO + const ratings = await Rating.find().sort({ createdAt: -1 }); + res.json({ ratings }); } catch (err) { next(err); } } // GET /api/ratings/:id -// TODO: implement per README.md section 2. export async function getRating(req, res, next) { try { - // TODO + if (!mongoose.isValidObjectId(req.params.id)) { + return res.status(400).json({ message: 'Invalid rating id' }); + } + const rating = await Rating.findById(req.params.id); + if (!rating) return res.status(404).json({ message: 'Rating not found' }); + res.json({ rating }); } catch (err) { next(err); } } // POST /api/ratings -// TODO: implement per README.md section 2. export async function createRating(req, res, next) { try { - // TODO - } catch (err) { next(err); } + const { bookCode, rating, note, ratedBy } = req.body; + const doc = await Rating.create({ bookCode, rating, note, ratedBy }); + res.status(201).json({ rating: doc }); + } catch (err) { + if (err.name === 'ValidationError') { + return res.status(400).json({ message: err.message }); + } + if (err.code === 11000) { + return res.status(409).json({ message: 'You already rated this book' }); + } + next(err); + } } // GET /api/ratings/summary?bookCode=BK101 -// TODO: implement per README.md section 3. export async function getRatingSummary(req, res, next) { try { - // TODO + const { bookCode } = req.query; + if (typeof bookCode !== 'string' || !bookCode) { + return res.status(400).json({ message: 'bookCode is required' }); + } + + const result = await Rating.aggregate([ + { $match: { bookCode } }, + { $group: { _id: '$bookCode', averageRating: { $avg: '$rating' }, ratingCount: { $sum: 1 } } } + ]); + + if (result.length === 0) { + return res.json({ bookCode, averageRating: 0, ratingCount: 0 }); + } + res.json({ + bookCode, + averageRating: result[0].averageRating, + ratingCount: result[0].ratingCount + }); } catch (err) { next(err); } -} +} \ No newline at end of file diff --git a/server/src/models/Rating.js b/server/src/models/Rating.js index c1e6a23..b1fd289 100644 --- a/server/src/models/Rating.js +++ b/server/src/models/Rating.js @@ -1,14 +1,15 @@ import mongoose from 'mongoose'; -// TODO: define the Rating schema per README.md section 1. - const ratingSchema = new mongoose.Schema( { - // TODO + bookCode: { type: String, required: true }, + rating: { type: Number, required: true, min: 1, max: 5 }, + note: { type: String }, + ratedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }, { timestamps: true } ); -// TODO: add the compound uniqueness constraint described in README.md section 1. +ratingSchema.index({ bookCode: 1, ratedBy: 1 }, { unique: true }); -export const Rating = mongoose.model('Rating', ratingSchema); +export const Rating = mongoose.model('Rating', ratingSchema); \ No newline at end of file diff --git a/server/src/routes/ratings.js b/server/src/routes/ratings.js index 8183a49..c2410c4 100644 --- a/server/src/routes/ratings.js +++ b/server/src/routes/ratings.js @@ -8,6 +8,9 @@ import { const router = Router(); -// TODO: wire up the three routes in README.md section 2 and the summary route in section 3. +router.get('/', getAllRatings); +router.post('/', createRating); +router.get('/summary', getRatingSummary); // must come before '/:id' +router.get('/:id', getRating); -export default router; +export default router; \ No newline at end of file