Skip to content

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

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

Created by: chi-jitera

Overview

This pull request implements the PATCH /books/:id endpoint, allowing for partial updates to book records. The implementation includes a new controller method and a corresponding service method to handle the logic for updating book fields.

Changes

  1. Controller Update:

    • Added the patchBook function in /controllers/bookController.js.
    • This function accepts PATCH requests, calls the service method for partial updates, and returns the updated document. It also handles error states, returning appropriate HTTP status codes.
    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 });
        }
    };
  2. Service Update:

    • Added the patchBook service function in /services/bookService.js.
    • This function performs a partial update on the Book model using Mongoose's findByIdAndUpdate with $set. It includes validation logic for the publishedYear field only if it is present in the patch data.
    exports.patchBook = async (bookId, patchData) => {
        if (typeof patchData.publishedYear !== 'undefined') {
            validateBookData({ publishedYear: patchData.publishedYear });
        }
        const book = await Book.findByIdAndUpdate(
            bookId,
            { $set: patchData },
            { new: true, runValidators: true }
        );
        if (!book) throw new Error('Book not found');
        return book;
    };

Conclusion

With these changes, the application now supports partial updates for book records, enhancing the flexibility of the API. The router configuration remains unchanged as it was already set up to call the new controller method.

Merge request reports