Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,20 @@
"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": {
"bcryptjs": "^2.4.3",
"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"
Expand Down
124 changes: 111 additions & 13 deletions server/src/controllers/ratingController.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,131 @@
import { Rating } from '../models/Rating.js';
import Joi from "joi";
import { Rating } from "../models/Rating.js";

const createSchema = Joi.object({
bookCode: Joi.string().required(),
rating: Joi.number().min(1).max(5).required(),
note: Joi.string().optional(),
ratedBy: Joi.string().optional(),
});

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); }
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);
}
}
63 changes: 45 additions & 18 deletions server/src/controllers/userController.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,46 @@
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
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
Expand All @@ -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);
}
}
36 changes: 29 additions & 7 deletions server/src/models/Rating.js
Original file line number Diff line number Diff line change
@@ -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);
Loading
Loading