[JITERA] Implement PATCH /books/:id Endpoint for Partial Book Updates
Created by: chi-jitera
Overview
This pull request implements the PATCH /books/:id endpoint to allow partial updates of book records. This addition follows the existing conventions of the project and ensures proper validation and error handling.
Changes Made
-
Updated Routes:
- Added a new route for PATCH requests in
/routes/bookRoutes.js:router.patch('/books/:id', bookController.patchBook); // Added PATCH route
- Added a new route for PATCH requests in
-
Controller Method:
- Implemented the
patchBookmethod in/controllers/bookController.jsto handle incoming PATCH requests: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 }); } };
- Implemented the
-
Service Logic:
- Added the
patchBookservice method in/services/bookService.jsto perform the partial update using Mongoose'sfindByIdAndUpdate:exports.patchBook = async (bookId, updateData) => { if ('publishedYear' in updateData && updateData.publishedYear > new Date().getFullYear()) { throw new Error('Published year cannot be in the future.'); } const allowedFields = ['title', 'author', 'publishedYear', 'genre', 'available']; Object.keys(updateData).forEach(field => { if (!allowedFields.includes(field)) { throw new Error(`Field "${field}" cannot be updated.`); } }); const book = await Book.findByIdAndUpdate(bookId, { $set: updateData }, { new: true, runValidators: true }); if (!book) throw new Error('Book not found'); return book; };
- Added the
Conclusion
This implementation adheres to the project's coding standards and ensures that only allowed fields can be updated, with appropriate error handling for validation and not found scenarios. Please review the changes and let me know if any further modifications are needed.