From fd96ca83b87254a7d89ff666e6c87a647d0f4c5e Mon Sep 17 00:00:00 2001 From: Yassinsasso Date: Sat, 26 Sep 2026 13:37:33 +0300 Subject: [PATCH] feat: Adding the feedback model, feedbackController, and feedback routes --- server/src/controllers/feedbackController.js | 115 ++++++++++++++++--- server/src/models/Feedback.js | 40 ++++++- server/src/routes/feedback.js | 22 +++- 3 files changed, 154 insertions(+), 23 deletions(-) diff --git a/server/src/controllers/feedbackController.js b/server/src/controllers/feedbackController.js index e0f198fb..f9d53e2d 100644 --- a/server/src/controllers/feedbackController.js +++ b/server/src/controllers/feedbackController.js @@ -1,33 +1,116 @@ +import Joi from 'joi'; import { Feedback } from '../models/Feedback.js'; -// GET /api/feedback -// TODO: implement per README.md section 2. + +//Validation Schema for creating feedback. +//Ensures the request body contains the correct types and constraints before hitting the DB. +const createSchema = Joi.object({ + workshopCode: Joi.string().required(), + score: Joi.number().integer().min(1).max(5).required(), + comment: Joi.string().optional(), + // Validates that submittedBy is a 24-character hex string (standard MongoDB ObjectId format) + submittedBy: Joi.string().hex().length(24).optional(), +}); + + + //GET /api/feedback + //Retrieves all feedback entries from the database. export async function getAllFeedbacks(req, res, next) { try { - // TODO - } catch (err) { next(err); } + // .lean() is used here to return plain JavaScript objects instead of Mongoose documents, + // which is faster and uses less memory for read-only operations. + const feedbacks = await Feedback.find().lean(); + res.json({ feedbacks }); + } catch (err) { + // Pass errors to the global error handling middleware in app.js + next(err); + } } -// GET /api/feedback/:id -// TODO: implement per README.md section 2. + + //GET /api/feedback/:id + //Retrieves a single feedback entry by its unique MongoDB ID. export async function getFeedback(req, res, next) { try { - // TODO - } catch (err) { next(err); } + const feedback = await Feedback.findById(req.params.id).lean(); + + // If no document is found with the provided ID, return a 404 Not Found response. + if (!feedback) { + return res.status(404).json({ message: 'Feedback not found' }); + } + res.json({ feedback }); + } catch (err) { + next(err); + } } -// POST /api/feedback -// TODO: implement per README.md section 2. + + //POST /api/feedback + //Creates a new feedback entry after validating the request body. export async function createFeedback(req, res, next) { try { - // TODO - } catch (err) { next(err); } + // 1. Validate the incoming request body against the Joi schema. + const { value, error } = createSchema.validate(req.body); + if (error) { + // Return 400 Bad Request if validation fails, including the specific Joi error message. + return res.status(400).json({ message: error.message }); + } + + // 2. Save the validated data to MongoDB. + const feedback = await Feedback.create(value); + + // Return 201 Created and the created document. + res.status(201).json({ feedback }); + } catch (err) { + next(err); + } } -// GET /api/feedback/summary?workshopCode=WS101 -// TODO: implement per README.md section 3. + + //GET /api/feedback/summary?workshopCode=WS101 + //Calculates the average score and total count for a specific workshop using MongoDB Aggregation. export async function getFeedbackSummary(req, res, next) { try { - // TODO - } catch (err) { next(err); } + const { workshopCode } = req.query; + + // Ensure the workshopCode query parameter is provided. + if (!workshopCode) { + return res.status(400).json({ message: 'workshopCode is required' }); + } + + //MongoDB Aggregation Pipeline: + //1. $match: Filter documents to only include those matching the requested workshopCode. + //2. $group: Group all matching documents together (_id: null) and calculate: + // - averageScore: The mathematical average of the 'score' field. + // - feedbackCount: The total number of documents matched. + const stats = await Feedback.aggregate([ + { $match: { workshopCode } }, + { + $group: { + _id: null, + averageScore: { $avg: '$score' }, + feedbackCount: { $sum: 1 }, + }, + }, + ]); + + // If no feedback exists for the workshop, the stats array will be empty. + if (stats.length === 0) { + return res.json({ + workshopCode, + averageScore: 0, + feedbackCount: 0, + }); + } + + // Extract results from the first element of the aggregation array. + const { averageScore, feedbackCount } = stats[0]; + res.json({ + workshopCode, + averageScore, + feedbackCount, + }); + } catch (err) { + next(err); + } } diff --git a/server/src/models/Feedback.js b/server/src/models/Feedback.js index 33198e7a..8f04e3a2 100644 --- a/server/src/models/Feedback.js +++ b/server/src/models/Feedback.js @@ -1,14 +1,44 @@ import mongoose from 'mongoose'; -// TODO: define the Feedback schema per README.md section 1. - +/** + * Feedback Schema + * Represents a user's feedback for a specific workshop. + */ const feedbackSchema = new mongoose.Schema( { - // TODO + // The unique identifier for the workshop + workshopCode: { + type: String, + required: true, + }, + // The rating given to the workshop, must be between 1 and 5 + score: { + type: Number, + required: true, + min: 1, + max: 5, + }, + // Optional text feedback + comment: { + type: String, + }, + // Optional reference to the User who submitted the feedback + submittedBy: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + }, }, - { timestamps: true } + { + // Automatically adds createdAt and updatedAt fields + timestamps: true + } ); -// TODO: add the compound uniqueness constraint described in README.md section 1. + +// Compound Unique Index +// This ensures that a specific user (submittedBy) can only leave +// one piece of feedback for a specific workshop (workshopCode). +// If submittedBy is null, it still works as a unique constraint on workshopCode. +feedbackSchema.index({ workshopCode: 1, submittedBy: 1 }, { unique: true }); export const Feedback = mongoose.model('Feedback', feedbackSchema); diff --git a/server/src/routes/feedback.js b/server/src/routes/feedback.js index 0f96b8a1..3f8f9027 100644 --- a/server/src/routes/feedback.js +++ b/server/src/routes/feedback.js @@ -3,11 +3,29 @@ import { getAllFeedbacks, getFeedback, createFeedback, - getFeedbackSummary + getFeedbackSummary, } from '../controllers/feedbackController.js'; const router = Router(); -// TODO: wire up the three routes in README.md section 2 and the summary route in section 3. + +//Route: GET /api/feedback/summary +//Must be placed before /:id so that 'summary' is not treated as an ID. +router.get('/summary', getFeedbackSummary); + + +//Route: GET /api/feedback +//Retrieves all feedback records. +router.get('/', getAllFeedbacks); + + +//Route: POST /api/feedback +//Submits a new feedback record. +router.post('/', createFeedback); + + +//Route: GET /api/feedback/:id +//Retrieves a specific feedback record by its ID. +router.get('/:id', getFeedback); export default router;