[JITERA] Implement PATCH /books/:id for Partial Book Updates
Created by: chi-jitera
Overview
This pull request introduces support for partial updates of books in the codebase by implementing the PATCH method for the /books/:id endpoint. This enhancement allows clients to update only specific fields of a book without needing to send the entire book object.
Changes Made
-
controllers/bookController.js:
- Added the
patchBookcontroller method that handles incoming PATCH requests. This method calls thepatchBookservice function and returns the updated book or an error message if the update fails.
exports.patchBook = async (req, res) => { try { const book = await bookService.patchBook(req.params.id, req.body); res.json(book); } catch (error) { res.status(400).json({ error: error.message }); } }; - Added the
-
routes/bookRoutes.js:
- Added a new route mapping for the PATCH method to the
patchBookcontroller. This allows the application to handle PATCH requests at the specified endpoint.
router.patch('/books/:id', bookController.patchBook); - Added a new route mapping for the PATCH method to the
-
services/bookService.js:
- Implemented the
patchBookservice function that performs the partial update usingfindByIdAndUpdate. It checks if thepublishedYearfield is present in the update data and validates it accordingly. The function returns the updated book or throws an error if the book is not found.
exports.patchBook = async (bookId, updateData) => { if (updateData.hasOwnProperty('publishedYear')) { validateBookData(updateData); } const book = await Book.findByIdAndUpdate(bookId, { $set: updateData }, { new: true, runValidators: true }); if (!book) throw new Error('Book not found'); return book; }; - Implemented the
This implementation aligns precisely with the project's existing routes, controller, and service conventions for book management.