[JITERA] Implement PATCH route for partial book updates
Created by: chi-jitera
Overview
This pull request introduces a new PATCH route for updating book details partially. It allows clients to send only the fields they want to update, improving flexibility and efficiency in managing book records.
Changes
-
Updated
bookRoutes.js:- Added a new route
PATCH /books/:idthat utilizes theupdateBookPartialmethod from thebookController.
router.patch('/books/:id', bookController.updateBookPartial); // PATCH route added - Added a new route
-
Updated
bookController.js:- Implemented the
updateBookPartialcontroller method to handle partial updates. This method validates the incoming data and handles errors appropriately.
exports.updateBookPartial = async (req, res) => { try { const updatedBook = await bookService.updateBookPartial(req.params.id, req.body); res.json(updatedBook); } catch (error) { if (error.message === 'Book not found') { res.status(404).json({ error: error.message }); } else { res.status(400).json({ error: error.message }); } } }; - Implemented the
-
Updated
bookService.js:- Added the
updateBookPartialmethod to validate the incoming data, ensuring that only the provided fields are updated. It also checks for the validity of thepublishedYearand other fields.
const validatePartialBookData = (data) => { // Validation logic... }; exports.updateBookPartial = async (bookId, updateData) => { validatePartialBookData(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 enhances the API's capability to handle partial updates, making it more user-friendly and efficient.