Skip to content

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

chi le requested to merge feat/implement-patch-book-endpoint-1761519036 into main

Created by: chi-jitera

Overview

This pull request implements the PATCH /books/:id endpoint, allowing for partial updates to book records in the database. The implementation adheres to the project's standards for validation, response, and error handling.

Changes Made

  1. Route Definition:

    • Added the PATCH route in /routes/bookRoutes.js to handle requests for updating book records partially.
    router.patch('/books/:id', bookController.patchBook);
  2. Controller Method:

    • Implemented the patchBook method in /controllers/bookController.js. This method delegates the request to the service layer and handles errors 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. Service Logic:

    • Developed the patchBook method in /services/bookService.js. This method finds the book by ID, validates the publishedYear if present, applies the updates, and saves the book.
    exports.patchBook = async (bookId, updateData) => {
        const book = await Book.findById(bookId);
        if (!book) throw new Error('Book not found');
        if (updateData.hasOwnProperty('publishedYear')) {
            if (updateData.publishedYear > new Date().getFullYear()) {
                throw new Error('Published year cannot be in the future.');
            }
        }
        Object.keys(updateData).forEach((field) => {
            book[field] = updateData[field];
        });
        await book.save();
        return book;
    };
  4. Error Handling:

    • Ensured consistent error handling across the controller and service layers, returning 404 for not found errors and 400 for validation errors.

This implementation aligns with the project's documentation standards and enhances the API's functionality by allowing partial updates to book records.

Merge request reports