[JITERA] Add PATCH /books/:id endpoint for partial updates
Created by: chi-jitera
Overview
This pull request introduces a new PATCH endpoint for the Book API, allowing partial updates to book records. The implementation follows the existing structure of the project, ensuring consistency in error handling and validation.
Changes
-
Updated Routes:
- Added a new PATCH route in
/routes/bookRoutes.jsthat maps to thepatchBookcontroller function.
router.patch('/books/:id', bookController.patchBook); // <-- PATCH route added - Added a new PATCH route in
-
Controller Implementation:
- Implemented the
patchBookfunction in/controllers/bookController.jsto handle the logic for partial updates.
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 }); } }; - Implemented the
-
Service Method:
- Added the
patchBookmethod in/services/bookService.jsthat validates only the provided fields and performs the update using Mongoose's$setsyntax.
exports.patchBook = async (bookId, updateData) => { validateBookData(updateData); const book = await Book.findByIdAndUpdate(bookId, { $set: updateData }, { new: true, runValidators: true }); if (!book) throw new Error('Book not found'); return book; }; - Added the
This implementation allows users to update only the fields they provide in the request, enhancing the flexibility of the API while maintaining the existing validation logic.