Skip to content

[JITERA] Implement PATCH /books/:id Endpoint for Partial Book Updates

chi le requested to merge feat/implement-patch-books-endpoint-1757923700 into main

Created by: chi-jitera

Overview

This pull request introduces a new endpoint for partially updating book resources using the PATCH method. The implementation allows clients to update only the fields they provide, rather than requiring a complete replacement of the book resource.

Changes

  1. Update /routes/bookRoutes.js

    • Added a new route for PATCH requests to handle partial updates for books.
    router.patch('/books/:id', bookController.patchBook);
  2. Update /controllers/bookController.js

    • Implemented the patchBook controller method to handle incoming PATCH requests. This method calls the corresponding service method to perform the update.
    exports.patchBook = async (req, res) => {
        try {
            const updatedBook = await bookService.patchBook(req.params.id, req.body);
            res.json(updatedBook);
        } catch (error) {
            res.status(400).json({ error: error.message });
        }
    };
  3. Update /services/bookService.js

    • Added the patchBook service method to handle the logic for partial updates. This method validates the publishedYear field only if it is present in the request body and uses Mongoose's $set operator to update the specified fields.
    exports.patchBook = async (bookId, patchData) => {
        if (patchData.hasOwnProperty('publishedYear')) {
            validateBookData(patchData);
        }
        const book = await Book.findByIdAndUpdate(bookId, { $set: patchData }, { new: true, runValidators: true });
        if (!book) throw new Error('Book not found');
        return book;
    };

This implementation enhances the API by allowing more flexible updates to book resources, improving usability for clients that may only need to change specific fields.

Merge request reports