[JITERA] Implement PATCH /books/:id Endpoint for Partial Book Updates
Created by: chi-jitera
Overview
This pull request implements the PATCH /books/:id endpoint, allowing for partial updates to book records. The implementation includes a new controller method and a corresponding service method to handle the logic for updating book fields.
Changes
-
Controller Update:
- Added the
patchBookfunction in/controllers/bookController.js. - This function accepts PATCH requests, calls the service method for partial updates, and returns the updated document. It also handles error states, returning appropriate HTTP status codes.
exports.patchBook = async (req, res) => { try { const book = await bookService.patchBook(req.params.id, req.body); res.json(book); } catch (error) { const status = error.message === 'Book not found' ? 404 : 400; res.status(status).json({ error: error.message }); } }; - Added the
-
Service Update:
- Added the
patchBookservice function in/services/bookService.js. - This function performs a partial update on the Book model using Mongoose's
findByIdAndUpdatewith$set. It includes validation logic for thepublishedYearfield only if it is present in the patch data.
exports.patchBook = async (bookId, patchData) => { if (typeof patchData.publishedYear !== 'undefined') { validateBookData({ publishedYear: patchData.publishedYear }); } const book = await Book.findByIdAndUpdate( bookId, { $set: patchData }, { new: true, runValidators: true } ); if (!book) throw new Error('Book not found'); return book; }; - Added the
Conclusion
With these changes, the application now supports partial updates for book records, enhancing the flexibility of the API. The router configuration remains unchanged as it was already set up to call the new controller method.