Skip to content

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

chi le requested to merge feat/partial-update-books-1757516047 into main

Created by: chi-jitera

Overview

This pull request introduces support for partial updates of books in the codebase by implementing the PATCH method for the /books/:id endpoint. This enhancement allows clients to update only specific fields of a book without needing to send the entire book object.

Changes Made

  1. controllers/bookController.js:

    • Added the patchBook controller method that handles incoming PATCH requests. This method calls the patchBook service function and returns the updated book or an error message if the update fails.
    exports.patchBook = async (req, res) => {
        try {
            const book = await bookService.patchBook(req.params.id, req.body);
            res.json(book);
        } catch (error) {
            res.status(400).json({ error: error.message });
        }
    };
  2. routes/bookRoutes.js:

    • Added a new route mapping for the PATCH method to the patchBook controller. This allows the application to handle PATCH requests at the specified endpoint.
    router.patch('/books/:id', bookController.patchBook);
  3. services/bookService.js:

    • Implemented the patchBook service function that performs the partial update using findByIdAndUpdate. It checks if the publishedYear field is present in the update data and validates it accordingly. The function returns the updated book or throws an error if the book is not found.
    exports.patchBook = async (bookId, updateData) => {
        if (updateData.hasOwnProperty('publishedYear')) {
            validateBookData(updateData);
        }
        const book = await Book.findByIdAndUpdate(bookId, { $set: updateData }, { new: true, runValidators: true });
        if (!book) throw new Error('Book not found');
        return book;
    };

This implementation aligns precisely with the project's existing routes, controller, and service conventions for book management.

Merge request reports