[JITERA] Implement PATCH /books/:id Endpoint for Partial Book Updates
Created by: chi-jitera
Overview
This pull request introduces a new endpoint for partially updating book resources using the PATCH method. The implementation allows clients to update only the fields they provide, rather than requiring a complete replacement of the book resource.
Changes
-
Update
/routes/bookRoutes.js- Added a new route for PATCH requests to handle partial updates for books.
router.patch('/books/:id', bookController.patchBook); -
Update
/controllers/bookController.js- Implemented the
patchBookcontroller method to handle incoming PATCH requests. This method calls the corresponding service method to perform the update.
exports.patchBook = async (req, res) => { try { const updatedBook = await bookService.patchBook(req.params.id, req.body); res.json(updatedBook); } catch (error) { res.status(400).json({ error: error.message }); } }; - Implemented the
-
Update
/services/bookService.js- Added the
patchBookservice method to handle the logic for partial updates. This method validates thepublishedYearfield only if it is present in the request body and uses Mongoose's$setoperator to update the specified fields.
exports.patchBook = async (bookId, patchData) => { if (patchData.hasOwnProperty('publishedYear')) { validateBookData(patchData); } const book = await Book.findByIdAndUpdate(bookId, { $set: patchData }, { new: true, runValidators: true }); if (!book) throw new Error('Book not found'); return book; }; - Added the
This implementation enhances the API by allowing more flexible updates to book resources, improving usability for clients that may only need to change specific fields.