Skip to content

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

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

Created by: chi-jitera

Overview

This pull request implements the PATCH method for updating book records partially. It adds the necessary route, controller method, and service function to handle partial updates to book data.

Changes Made

  1. Updated /routes/bookRoutes.js:

    • Added a PATCH route for /books/:id that maps to the patchBook method in the bookController.
    router.patch('/books/:id', bookController.patchBook); // Added PATCH
  2. Updated /controllers/bookController.js:

    • Implemented the patchBook handler that calls the patchBook method from the bookService.
    • Added error handling to return a 404 status for not found errors and a 400 status for other errors.
    exports.patchBook = async (req, res) => {
        try {
            const book = await bookService.patchBook(req.params.id, req.body);
            res.json(book);
        } catch (error) {
            res.status(error.message === "Book not found" ? 404 : 400).json({ error: error.message });
        }
    };
  3. Updated /services/bookService.js:

    • Created the patchBook function to perform a partial update using Mongoose's .findByIdAndUpdate with $set.
    • Included minimal validation to ensure that the publishedYear is not set in the future.
    exports.patchBook = async (bookId, patchData) => {
        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 allows for more flexible updates to book records, enhancing the API's usability.

Merge request reports