[JITERA] Implement PATCH /books/:id for Partial Book Updates
Created by: chi-jitera
Overview
This pull request implements the PATCH /books/:id endpoint to allow partial updates of book records. The changes ensure that only the fields provided in the request body are updated, while also maintaining proper error handling and validation.
Changes Made
-
Update Route Definition:
- Added a PATCH route for
/books/:idinroutes/bookRoutes.jsto support partial book updates.
router.patch('/books/:id', bookController.patchBook); - Added a PATCH route for
-
Confirm Controller Function:
- The existing
patchBookmethod incontrollers/bookController.jshas been confirmed to handle the request correctly, delegating to the service layer and managing error responses appropriately.
exports.patchBook = async (req, res) => { try { const book = await bookService.patchBook(req.params.id, req.body); res.json(book); } catch (error) { const status = error.message === 'Book not found' ? 404 : 400; res.status(status).json({ error: error.message }); } }; - The existing
-
Confirm Service Logic:
- The
patchBookmethod inservices/bookService.jshas been confirmed to implement the correct logic for partial updates, including validation for thepublishedYearfield and ensuring only present fields are updated.
exports.patchBook = async (bookId, updateData) => { const book = await Book.findById(bookId); if (!book) throw new Error('Book not found'); // Validate only present fields if (updateData.hasOwnProperty('publishedYear')) { if (updateData.publishedYear > new Date().getFullYear()) { throw new Error('Published year cannot be in the future.'); } } // Update book object only with present fields Object.keys(updateData).forEach((field) => { book[field] = updateData[field]; }); await book.save(); return book; }; - The
-
Confirm Model Compliance:
- The Book schema in
models/Book.jshas been confirmed to include all required fields: title, author, publishedYear, genre, and available.
- The Book schema in
Summary
- The PATCH /books/:id route is now present and properly wired.
- The controller (
patchBook) and service logic are implemented per technical requirements. - Schema and error handling are aligned with project/documentation guidelines.