Skip to content

[JITERA] Add PATCH /books/:id endpoint for partial updates

Created by: chi-jitera

Overview

This pull request introduces a new PATCH endpoint for the Book API, allowing partial updates to book records. The implementation follows the existing structure of the project, ensuring consistency in error handling and validation.

Changes

  1. Updated Routes:

    • Added a new PATCH route in /routes/bookRoutes.js that maps to the patchBook controller function.
    router.patch('/books/:id', bookController.patchBook); // <-- PATCH route added
  2. Controller Implementation:

    • Implemented the patchBook function in /controllers/bookController.js to handle the logic for partial updates.
    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 });
        }
    };
  3. Service Method:

    • Added the patchBook method in /services/bookService.js that validates only the provided fields and performs the update using Mongoose's $set syntax.
    exports.patchBook = async (bookId, updateData) => {
        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 allows users to update only the fields they provide in the request, enhancing the flexibility of the API while maintaining the existing validation logic.

Merge request reports