[JITERA] Implement PATCH /books/:id for Partial Updates
Created by: chi-jitera
Overview
This pull request implements the PATCH method for updating book records partially. It adds the necessary route, controller method, and service function to handle partial updates to book data.
Changes Made
-
Updated
/routes/bookRoutes.js:- Added a PATCH route for
/books/:idthat maps to thepatchBookmethod in thebookController.
router.patch('/books/:id', bookController.patchBook); // Added PATCH - Added a PATCH route for
-
Updated
/controllers/bookController.js:- Implemented the
patchBookhandler that calls thepatchBookmethod from thebookService. - Added error handling to return a 404 status for not found errors and a 400 status for other errors.
exports.patchBook = async (req, res) => { try { const book = await bookService.patchBook(req.params.id, req.body); res.json(book); } catch (error) { res.status(error.message === "Book not found" ? 404 : 400).json({ error: error.message }); } }; - Implemented the
-
Updated
/services/bookService.js:- Created the
patchBookfunction to perform a partial update using Mongoose's.findByIdAndUpdatewith$set. - Included minimal validation to ensure that the
publishedYearis not set in the future.
exports.patchBook = async (bookId, patchData) => { validateBookData(patchData); const book = await Book.findByIdAndUpdate(bookId, { $set: patchData }, { new: true, runValidators: true }); if (!book) throw new Error('Book not found'); return book; }; - Created the
This implementation allows for more flexible updates to book records, enhancing the API's usability.