Skip to content

[JITERA] Implement PATCH route for partial book updates

chi le requested to merge feat/add-patch-route-for-partial-updates-1758533992 into main

Created by: chi-jitera

Overview

This pull request introduces a new PATCH route for updating book details partially. It allows clients to send only the fields they want to update, improving flexibility and efficiency in managing book records.

Changes

  1. Updated bookRoutes.js:

    • Added a new route PATCH /books/:id that utilizes the updateBookPartial method from the bookController.
    router.patch('/books/:id', bookController.updateBookPartial); // PATCH route added
  2. Updated bookController.js:

    • Implemented the updateBookPartial controller method to handle partial updates. This method validates the incoming data and handles errors appropriately.
    exports.updateBookPartial = async (req, res) => {
        try {
            const updatedBook = await bookService.updateBookPartial(req.params.id, req.body);
            res.json(updatedBook);
        } catch (error) {
            if (error.message === 'Book not found') {
                res.status(404).json({ error: error.message });
            } else {
                res.status(400).json({ error: error.message });
            }
        }
    };
  3. Updated bookService.js:

    • Added the updateBookPartial method to validate the incoming data, ensuring that only the provided fields are updated. It also checks for the validity of the publishedYear and other fields.
    const validatePartialBookData = (data) => {
        // Validation logic...
    };
    
    exports.updateBookPartial = async (bookId, updateData) => {
        validatePartialBookData(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 enhances the API's capability to handle partial updates, making it more user-friendly and efficient.

Merge request reports