From a32912cd2b182607932a7348c121fab15a2aa683 Mon Sep 17 00:00:00 2001 From: Adel Hamed Date: Tue, 29 Sep 2026 12:21:58 +0300 Subject: [PATCH 1/2] temporary commit because time is up --- server/package-lock.json | 2 + server/src/controllers/ratingController.js | 77 +++++++++++++++++++--- server/src/models/Rating.js | 36 ++++++++-- 3 files changed, 98 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..b4f2faf 100644 --- a/server/src/controllers/ratingController.js +++ b/server/src/controllers/ratingController.js @@ -1,33 +1,90 @@ -import { Rating } from '../models/Rating.js'; +import Joi from "joi"; +import { Rating } from "../models/Rating.js"; + +const createSchema = Joi.object({ + bookCode: Joi.string().min(5).max(5).required(), + rating: Joi.number().min(1).max(5).required(), + note: Joi.string().min(2).max(100).optional(), // I guess + ratedBy: Joi.string(), // IDK +}); + +const updateSchema = Joi.object({ + rating: Joi.number().min(1).max(5), + note: Joi.string().min(2).max(100), // I guess + ratedBy: Joi.string(), // IDK +}); + +function publicRating(r) { + return { + id: r._id.toString(), + bookCode: r.bookCode, + rating: r.rating, + note: r.note, + ratedBy: r.ratedBy, + createdAt: r.createdAt, + }; +} // GET /api/ratings -// TODO: implement per README.md section 2. export async function getAllRatings(req, res, next) { try { - // TODO - } catch (err) { next(err); } + const ratings = await Rating.find().sort({ createdAt: -1 }).lean(); + res.status(200).json({ ratings: ratings.map(publicRating) }); + } catch (err) { + next(err); + } } // GET /api/ratings/:id // TODO: implement per README.md section 2. export async function getRating(req, res, next) { try { - // TODO - } catch (err) { next(err); } + const rating = await Rating.findById(req.params.id); + if (!rating) return res.status(404).json({ message: "Rating not found" }); + res.status(200).json({ rating: publicRating(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 { value, error } = createSchema.validate(req.body); + if (error) return res.status(400).json({ message: error.message }); + + const existing = await Rating.findOne({ + bookCode: value.bookCode, + ratedBy: value.ratedBy, + }); + if (existing) + return res.status(409).json({ message: "Rating already exists" }); + + const Rating = await Rating.create({ + bookCode: value.bookCode, + rating: value.rating, + note: value.note, + ratedBy: value.ratedBy, + }); + res.status(201).json({ rating: publicRating(rating) }); + } catch (err) { + next(err); + } } // GET /api/ratings/summary?bookCode=BK101 // TODO: implement per README.md section 3. export async function getRatingSummary(req, res, next) { try { - // TODO - } catch (err) { next(err); } + try { + const rating = await Rating.find(bookCode == req); + if (!rating) return res.status(404).json({ message: "Rating not found" }); + res.status(200).json({ rating: publicRating(rating) }); + } catch (err) { + next(err); + } + } catch (err) { + next(err); + } } diff --git a/server/src/models/Rating.js b/server/src/models/Rating.js index c1e6a23..70fe156 100644 --- a/server/src/models/Rating.js +++ b/server/src/models/Rating.js @@ -1,14 +1,36 @@ -import mongoose from 'mongoose'; - -// TODO: define the Rating schema per README.md section 1. +import mongoose from "mongoose"; const ratingSchema = new mongoose.Schema( { - // TODO + bookCode: { + type: String, + required: true, + }, + + rating: { + type: Number, + required: true, + min: 1, + max: 5, + }, + + note: { + type: String, + required: false, + }, + + ratedBy: { + type: mongoose.Schema.Types.ObjectId, + ref: "User", + required: false, + }, + }, + { + timestamps: true, }, - { timestamps: true } ); -// TODO: add the compound uniqueness constraint described in README.md section 1. +// A user can only rate a specific book once. +ratingSchema.index({ bookCode: 1, ratedBy: 1 }, { unique: true }); -export const Rating = mongoose.model('Rating', ratingSchema); +export const Rating = mongoose.model("Rating", ratingSchema); From 49494a7b57c95cf52892788a4a463791e305e446 Mon Sep 17 00:00:00 2001 From: Adel Hamed Date: Tue, 29 Sep 2026 12:44:30 +0300 Subject: [PATCH 2/2] successfully tested using npm test and now submitting the final version --- server/package-lock.json | 26 ++++++ server/package.json | 7 +- server/src/controllers/ratingController.js | 93 ++++++++++++++++------ server/src/controllers/userController.js | 63 ++++++++++----- server/src/routes/ratings.js | 16 ++-- 5 files changed, 153 insertions(+), 52 deletions(-) diff --git a/server/package-lock.json b/server/package-lock.json index 0c230a0..26a5c93 100644 --- a/server/package-lock.json +++ b/server/package-lock.json @@ -17,6 +17,7 @@ "morgan": "^1.10.0" }, "devDependencies": { + "cross-env": "^10.1.0", "jest": "^29.7.0", "nodemon": "^3.1.0", "supertest": "^7.1.1" @@ -569,6 +570,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@epic-web/invariant": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz", + "integrity": "sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==", + "dev": true, + "license": "MIT" + }, "node_modules/@hapi/hoek": { "version": "9.3.0", "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", @@ -1871,6 +1879,24 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/cross-env": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz", + "integrity": "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@epic-web/invariant": "^1.0.0", + "cross-spawn": "^7.0.6" + }, + "bin": { + "cross-env": "dist/bin/cross-env.js", + "cross-env-shell": "dist/bin/cross-env-shell.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", diff --git a/server/package.json b/server/package.json index eeec22e..bf56325 100644 --- a/server/package.json +++ b/server/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "nodemon src/index.js", "start": "node src/index.js", - "test": "NODE_OPTIONS=--experimental-vm-modules jest --runInBand", + "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand", "grade": "NODE_OPTIONS=--experimental-vm-modules jest --runInBand --verbose" }, "dependencies": { @@ -13,11 +13,12 @@ "cors": "^2.8.5", "dotenv": "^16.4.5", "express": "^4.19.2", + "joi": "^17.12.3", "mongoose": "^8.6.0", - "morgan": "^1.10.0", - "joi": "^17.12.3" + "morgan": "^1.10.0" }, "devDependencies": { + "cross-env": "^10.1.0", "jest": "^29.7.0", "nodemon": "^3.1.0", "supertest": "^7.1.1" diff --git a/server/src/controllers/ratingController.js b/server/src/controllers/ratingController.js index b4f2faf..ae4eb07 100644 --- a/server/src/controllers/ratingController.js +++ b/server/src/controllers/ratingController.js @@ -2,16 +2,10 @@ import Joi from "joi"; import { Rating } from "../models/Rating.js"; const createSchema = Joi.object({ - bookCode: Joi.string().min(5).max(5).required(), + bookCode: Joi.string().required(), rating: Joi.number().min(1).max(5).required(), - note: Joi.string().min(2).max(100).optional(), // I guess - ratedBy: Joi.string(), // IDK -}); - -const updateSchema = Joi.object({ - rating: Joi.number().min(1).max(5), - note: Joi.string().min(2).max(100), // I guess - ratedBy: Joi.string(), // IDK + note: Joi.string().optional(), + ratedBy: Joi.string().optional(), }); function publicRating(r) { @@ -29,61 +23,108 @@ function publicRating(r) { export async function getAllRatings(req, res, next) { try { const ratings = await Rating.find().sort({ createdAt: -1 }).lean(); - res.status(200).json({ ratings: ratings.map(publicRating) }); + + res.status(200).json({ + ratings: ratings.map(publicRating), + }); } catch (err) { next(err); } } // GET /api/ratings/:id -// TODO: implement per README.md section 2. export async function getRating(req, res, next) { try { const rating = await Rating.findById(req.params.id); - if (!rating) return res.status(404).json({ message: "Rating not found" }); - res.status(200).json({ rating: publicRating(rating) }); + + if (!rating) { + return res.status(404).json({ + message: "Rating not found", + }); + } + + res.status(200).json({ + rating: publicRating(rating), + }); } catch (err) { next(err); } } // POST /api/ratings -// TODO: implement per README.md section 2. export async function createRating(req, res, next) { try { const { value, error } = createSchema.validate(req.body); - if (error) return res.status(400).json({ message: error.message }); + + if (error) { + return res.status(400).json({ + message: error.message, + }); + } const existing = await Rating.findOne({ bookCode: value.bookCode, ratedBy: value.ratedBy, }); - if (existing) - return res.status(409).json({ message: "Rating already exists" }); - const Rating = await Rating.create({ + if (existing) { + return res.status(409).json({ + message: "Rating already exists", + }); + } + + const rating = await Rating.create({ bookCode: value.bookCode, rating: value.rating, note: value.note, ratedBy: value.ratedBy, }); - res.status(201).json({ rating: publicRating(rating) }); + + res.status(201).json({ + rating: publicRating(rating), + }); } catch (err) { next(err); } } // GET /api/ratings/summary?bookCode=BK101 -// TODO: implement per README.md section 3. export async function getRatingSummary(req, res, next) { try { - try { - const rating = await Rating.find(bookCode == req); - if (!rating) return res.status(404).json({ message: "Rating not found" }); - res.status(200).json({ rating: publicRating(rating) }); - } catch (err) { - next(err); + const { bookCode } = req.query; + + if (!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.status(200).json({ + bookCode, + averageRating: 0, + ratingCount: 0, + }); + } + + res.status(200).json({ + bookCode, + averageRating: result[0].averageRating, + ratingCount: result[0].ratingCount, + }); } catch (err) { next(err); } diff --git a/server/src/controllers/userController.js b/server/src/controllers/userController.js index 1926b74..0ea9b10 100644 --- a/server/src/controllers/userController.js +++ b/server/src/controllers/userController.js @@ -1,20 +1,25 @@ -import Joi from 'joi'; -import bcrypt from 'bcryptjs'; -import { User } from '../models/User.js'; +import Joi from "joi"; +import bcrypt from "bcryptjs"; +import { User } from "../models/User.js"; const createSchema = Joi.object({ name: Joi.string().min(2).max(60).required(), email: Joi.string().email().required(), - password: Joi.string().min(6).required() + password: Joi.string().min(6).required(), }); const updateSchema = Joi.object({ name: Joi.string().min(2).max(60), - email: Joi.string().email() + email: Joi.string().email(), }); function publicUser(u) { - return { id: u._id.toString(), name: u.name, email: u.email, createdAt: u.createdAt }; + return { + id: u._id.toString(), + name: u.name, + email: u.email, + createdAt: u.createdAt, + }; } // GET /api/users @@ -22,16 +27,20 @@ export async function getAllUsers(req, res, next) { try { const users = await User.find().sort({ createdAt: -1 }).lean(); res.json({ users: users.map(publicUser) }); - } catch (err) { next(err); } + } catch (err) { + next(err); + } } // GET /api/users/:id export async function getUser(req, res, next) { try { const user = await User.findById(req.params.id); - if (!user) return res.status(404).json({ message: 'User not found' }); + if (!user) return res.status(404).json({ message: "User not found" }); res.json({ user: publicUser(user) }); - } catch (err) { next(err); } + } catch (err) { + next(err); + } } // POST /api/users @@ -41,31 +50,49 @@ export async function createUser(req, res, next) { if (error) return res.status(400).json({ message: error.message }); const existing = await User.findOne({ email: value.email }); - if (existing) return res.status(409).json({ message: 'Email already used' }); + if (existing) + return res.status(409).json({ message: "Email already used" }); const password = await bcrypt.hash(value.password, 10); - const user = await User.create({ name: value.name, email: value.email, password }); + const user = await User.create({ + name: value.name, + email: value.email, + password, + }); res.status(201).json({ user: publicUser(user) }); - } catch (err) { next(err); } + } catch (err) { + next(err); + } } // PATCH /api/users/:id export async function updateUser(req, res, next) { try { - const { value, error } = updateSchema.validate(req.body, { abortEarly: false, stripUnknown: true }); + const { value, error } = updateSchema.validate(req.body, { + abortEarly: false, + stripUnknown: true, + }); if (error) return res.status(400).json({ message: error.message }); - const doc = await User.findByIdAndUpdate(req.params.id, { $set: value }, { new: true, runValidators: true }); - if (!doc) return res.status(404).json({ message: 'User not found' }); + const doc = await User.findByIdAndUpdate( + req.params.id, + { $set: value }, + { new: true, runValidators: true }, + ); + if (!doc) return res.status(404).json({ message: "User not found" }); res.json({ user: publicUser(doc) }); - } catch (err) { next(err); } + } catch (err) { + next(err); + } } // DELETE /api/users/:id export async function deleteUser(req, res, next) { try { const doc = await User.findByIdAndDelete(req.params.id); - if (!doc) return res.status(404).json({ message: 'User not found' }); + if (!doc) return res.status(404).json({ message: "User not found" }); res.json({ ok: true }); - } catch (err) { next(err); } + } catch (err) { + next(err); + } } diff --git a/server/src/routes/ratings.js b/server/src/routes/ratings.js index 8183a49..f1459b7 100644 --- a/server/src/routes/ratings.js +++ b/server/src/routes/ratings.js @@ -1,13 +1,19 @@ -import { Router } from 'express'; +import express from "express"; import { getAllRatings, getRating, createRating, - getRatingSummary -} from '../controllers/ratingController.js'; + getRatingSummary, +} from "../controllers/ratingController.js"; -const router = Router(); +const router = express.Router(); -// TODO: wire up the three routes in README.md section 2 and the summary route in section 3. +// 1. Static/Specific endpoints FIRST +router.get("/", getAllRatings); +router.post("/", createRating); +router.get("/summary", getRatingSummary); // <--- MUST BE ABOVE /:id + +// 2. Dynamic parameter endpoints LAST +router.get("/:id", getRating); export default router;