Skip to content

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

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

Created by: chi-jitera

Overview

This pull request implements the PATCH /books/:id endpoint to allow partial updates of book records. This addition follows the existing conventions of the project and ensures proper validation and error handling.

Changes Made

  1. Updated Routes:

    • Added a new route for PATCH requests in /routes/bookRoutes.js:
      router.patch('/books/:id', bookController.patchBook); // Added PATCH route
  2. Controller Method:

    • Implemented the patchBook method in /controllers/bookController.js to handle incoming PATCH requests:
      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:

    • Added the patchBook service method in /services/bookService.js to perform the partial update using Mongoose's findByIdAndUpdate:
      exports.patchBook = async (bookId, updateData) => {
          if ('publishedYear' in updateData && updateData.publishedYear > new Date().getFullYear()) {
              throw new Error('Published year cannot be in the future.');
          }
          const allowedFields = ['title', 'author', 'publishedYear', 'genre', 'available'];
          Object.keys(updateData).forEach(field => {
              if (!allowedFields.includes(field)) {
                  throw new Error(`Field "${field}" cannot be updated.`);
              }
          });
          const book = await Book.findByIdAndUpdate(bookId, { $set: updateData }, { new: true, runValidators: true });
          if (!book) throw new Error('Book not found');
          return book;
      };

Conclusion

This implementation adheres to the project's coding standards and ensures that only allowed fields can be updated, with appropriate error handling for validation and not found scenarios. Please review the changes and let me know if any further modifications are needed.

Merge request reports