[JITERA] Refactor Book Update Endpoint
Created by: chi-jitera
Overview
This pull request refactors the Book Update endpoint to align with the documented API specifications and improve error handling and validation. The changes ensure that the update flow is consistent and modular, following the structure: Route → Controller → Service → Mongoose Model.
Changes
-
Route Definition:
- Updated
/routes/bookRoutes.jsto define the PUT route for updating a book by ID. TheupdateBookcontroller is now properly imported and applied to the route.
// /routes/bookRoutes.js const express = require('express'); const router = express.Router(); const bookController = require('../controllers/bookController'); // PUT /books/:id - Update a book by ID router.put('/books/:id', bookController.updateBook); module.exports = router; - Updated
-
Controller Logic:
- Refactored the
updateBookcontroller in/controllers/bookController.jsto extract parameters and body data, utilize the service for updating, check for book existence, and return appropriate error messages.
// /controllers/bookController.js const bookService = require('../services/bookService'); exports.updateBook = async (req, res) => { const { id } = req.params; const updateData = req.body; try { const updatedBook = await bookService.updateBook(id, updateData); if (!updatedBook) { return res.status(404).json({ error: 'Book not found' }); } return res.status(200).json(updatedBook); } catch (err) { if (err.name === 'ValidationError') { return res.status(400).json({ error: err.message }); } return res.status(500).json({ error: 'Internal Server Error' }); } }; - Refactored the
-
Service Layer:
- Updated the
updateBookservice in/services/bookService.jsto use Mongoose'sfindByIdAndUpdatemethod with validation, ensuring that only existing books are updated.
// /services/bookService.js const Book = require('../models/Book'); exports.updateBook = async (id, updateData) => { const options = { new: true, runValidators: true }; const updatedBook = await Book.findByIdAndUpdate(id, updateData, options).lean(); return updatedBook; }; - Updated the
-
Mongoose Model:
- Ensured that the schema in
/models/Book.jsmatches the documented fields and maintains compatibility with update operations.
// /models/Book.js const mongoose = require('mongoose'); const bookSchema = new mongoose.Schema({ title: { type: String, required: true }, author: String, publishedDate: Date, genre: String }); module.exports = mongoose.model('Book', bookSchema); - Ensured that the schema in
Summary
- The refactor adheres to the documented API flow and conventions.
- It ensures that only provided fields in the request body are updated.
- The endpoint now returns appropriate HTTP status codes: 200 for success, 404 for not found, and 400 for validation errors.
- All code changes are modular and maintain the project's coding style.