[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 in the database. The implementation adheres to the project's standards for validation, response, and error handling.
Changes Made
-
Route Definition:
- Added the PATCH route in
/routes/bookRoutes.jsto handle requests for updating book records partially.
router.patch('/books/:id', bookController.patchBook); - Added the PATCH route in
-
Controller Method:
- Implemented the
patchBookmethod in/controllers/bookController.js. This method delegates the request to the service layer and handles errors appropriately.
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:
- Developed the
patchBookmethod in/services/bookService.js. This method finds the book by ID, validates thepublishedYearif present, applies the updates, and saves the book.
exports.patchBook = async (bookId, updateData) => { const book = await Book.findById(bookId); if (!book) throw new Error('Book not found'); if (updateData.hasOwnProperty('publishedYear')) { if (updateData.publishedYear > new Date().getFullYear()) { throw new Error('Published year cannot be in the future.'); } } Object.keys(updateData).forEach((field) => { book[field] = updateData[field]; }); await book.save(); return book; }; - Developed the
-
Error Handling:
- Ensured consistent error handling across the controller and service layers, returning 404 for not found errors and 400 for validation errors.
This implementation aligns with the project's documentation standards and enhances the API's functionality by allowing partial updates to book records.