Skip to content

[JITERA] Add PATCH endpoint for partial updates to books

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

Created by: chi-jitera

Overview

This pull request introduces a new PATCH endpoint for the /books/:id route, allowing for partial updates to book documents in the database. This enhancement follows the existing structure and conventions of the codebase, ensuring consistency and maintainability.

Changes

  1. Updated Routes:

    • Added a PATCH route in /routes/bookRoutes.js that maps to the patchBook method in the bookController.
    router.patch('/books/:id', bookController.patchBook); // ← PATCH endpoint
  2. Controller Method:

    • Implemented the patchBook method in /controllers/bookController.js. This method calls the patchBook service logic and includes error handling that adheres to existing conventions.
    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 Logic:

    • Added the patchBook method in /services/bookService.js to handle the partial update logic. This method validates the publishedYear if present and uses findByIdAndUpdate with $set to update only the specified fields.
    exports.patchBook = async (bookId, patchData) => {
        if (patchData.publishedYear !== undefined) {
            if (patchData.publishedYear > new Date().getFullYear()) {
                throw new Error('Published year cannot be in the future.');
            }
        }
        const book = await Book.findByIdAndUpdate(
            bookId,
            { $set: patchData },
            { new: true, runValidators: true }
        );
        if (!book) throw new Error('Book not found');
        return book;
    };

Summary

  • This update allows for partial updates to book records, enhancing the flexibility of the API.
  • Validation is enforced on the publishedYear field to prevent future dates.
  • The implementation follows existing error handling and response conventions, ensuring a seamless integration into the current codebase.

Let me know if you would like to discuss further refinements or if tests are needed for this feature.

Merge request reports