Skip to content

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

chi le requested to merge feat/patch-books-endpoint-1761519170 into main

Created by: chi-jitera

Overview

This pull request implements a new PATCH endpoint for updating book records partially. The new endpoint allows clients to send only the fields they wish to update, while still enforcing validation rules, such as ensuring the published year is not set in the future.

Changes

  1. Updated bookRoutes.js:

    • Added a PATCH route for /books/:id that maps to the patchBook method in the bookController. This follows RESTful design conventions by placing the PATCH route after the PUT route.
    router.patch('/books/:id', bookController.patchBook);
  2. Implemented patchBook in bookController.js:

    • Created a new controller method patchBook that handles incoming PATCH requests. It calls the patchBook method from the bookService and includes error handling to return appropriate status codes for validation errors and missing books.
    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. Added patchBook in bookService.js:

    • Implemented the patchBook service method that allows partial updates to book records. It validates the publishedYear if provided and ensures it is not in the future. The method uses Mongoose's findByIdAndUpdate with runValidators to apply schema validation.
    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, patchData, { new: true, runValidators: true });
        if (!book) throw new Error('Book not found');
        return book;
    };

This implementation adheres to the project's coding standards and RESTful principles, ensuring that the API remains consistent and reliable.

Merge request reports