[JITERA] Add PATCH endpoint for partial updates to books
Created by: chi-jitera
Overview
This pull request introduces a new PATCH endpoint for the /books/:id route, allowing for partial updates to book documents in the database. This enhancement follows the existing structure and conventions of the codebase, ensuring consistency and maintainability.
Changes
-
Updated Routes:
- Added a PATCH route in
/routes/bookRoutes.jsthat maps to thepatchBookmethod in thebookController.
router.patch('/books/:id', bookController.patchBook); // ← PATCH endpoint - Added a PATCH route in
-
Controller Method:
- Implemented the
patchBookmethod in/controllers/bookController.js. This method calls thepatchBookservice logic and includes error handling that adheres to existing conventions.
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 Logic:
- Added the
patchBookmethod in/services/bookService.jsto handle the partial update logic. This method validates thepublishedYearif present and usesfindByIdAndUpdatewith$setto update only the specified fields.
exports.patchBook = async (bookId, patchData) => { if (patchData.publishedYear !== undefined) { if (patchData.publishedYear > new Date().getFullYear()) { throw new Error('Published year cannot be in the future.'); } } const book = await Book.findByIdAndUpdate( bookId, { $set: patchData }, { new: true, runValidators: true } ); if (!book) throw new Error('Book not found'); return book; }; - Added the
Summary
- This update allows for partial updates to book records, enhancing the flexibility of the API.
- Validation is enforced on the
publishedYearfield to prevent future dates. - The implementation follows existing error handling and response conventions, ensuring a seamless integration into the current codebase.
Let me know if you would like to discuss further refinements or if tests are needed for this feature.