[JITERA] Add PATCH /books/:id endpoint for partial updates
Created by: chi-jitera
Overview
This pull request implements a new PATCH endpoint for updating book records partially. The new endpoint allows clients to send only the fields they wish to update, while still enforcing validation rules, such as ensuring the published year is not set in the future.
Changes
-
Updated
bookRoutes.js:- Added a PATCH route for
/books/:idthat maps to thepatchBookmethod in thebookController. This follows RESTful design conventions by placing the PATCH route after the PUT route.
router.patch('/books/:id', bookController.patchBook); - Added a PATCH route for
-
Implemented
patchBookinbookController.js:- Created a new controller method
patchBookthat handles incoming PATCH requests. It calls thepatchBookmethod from thebookServiceand includes error handling to return appropriate status codes for validation errors and missing books.
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 }); } }; - Created a new controller method
-
Added
patchBookinbookService.js:- Implemented the
patchBookservice method that allows partial updates to book records. It validates thepublishedYearif provided and ensures it is not in the future. The method uses Mongoose'sfindByIdAndUpdatewithrunValidatorsto apply schema validation.
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, patchData, { new: true, runValidators: true }); if (!book) throw new Error('Book not found'); return book; }; - Implemented the
This implementation adheres to the project's coding standards and RESTful principles, ensuring that the API remains consistent and reliable.