Skip to content

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

chi le requested to merge feat/partial-book-update-1763465993 into feat/-1762918120

Created by: chi-jitera

Overview

This pull request implements the PATCH /books/:id endpoint to allow partial updates of book records. The changes ensure that only the fields provided in the request body are updated, while also maintaining proper error handling and validation.

Changes Made

  1. Update Route Definition:

    • Added a PATCH route for /books/:id in routes/bookRoutes.js to support partial book updates.
    router.patch('/books/:id', bookController.patchBook);
  2. Confirm Controller Function:

    • The existing patchBook method in controllers/bookController.js has been confirmed to handle the request correctly, delegating to the service layer and managing error responses appropriately.
    exports.patchBook = async (req, res) => {
        try {
            const book = await bookService.patchBook(req.params.id, req.body);
            res.json(book);
        } catch (error) {
            const status = error.message === 'Book not found' ? 404 : 400;
            res.status(status).json({ error: error.message });
        }
    };
  3. Confirm Service Logic:

    • The patchBook method in services/bookService.js has been confirmed to implement the correct logic for partial updates, including validation for the publishedYear field and ensuring only present fields are updated.
    exports.patchBook = async (bookId, updateData) => {
        const book = await Book.findById(bookId);
        if (!book) throw new Error('Book not found');
        // Validate only present fields
        if (updateData.hasOwnProperty('publishedYear')) {
            if (updateData.publishedYear > new Date().getFullYear()) {
                throw new Error('Published year cannot be in the future.');
            }
        }
        // Update book object only with present fields
        Object.keys(updateData).forEach((field) => {
            book[field] = updateData[field];
        });
        await book.save();
        return book;
    };
  4. Confirm Model Compliance:

    • The Book schema in models/Book.js has been confirmed to include all required fields: title, author, publishedYear, genre, and available.

Summary

  • The PATCH /books/:id route is now present and properly wired.
  • The controller (patchBook) and service logic are implemented per technical requirements.
  • Schema and error handling are aligned with project/documentation guidelines.

Merge request reports