Skip to content

[JITERA] Implement PATCH /books/:id for partial updates to book records

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

Created by: chi-jitera

Overview

This pull request implements the PATCH /books/:id endpoint in the Express backend to allow partial updates to book records. The implementation adheres to the specifications outlined in the API documentation.

Changes Made

  1. Updated Book Model:

    • Modified /models/book.js to include the missing fields publishedYear (Number, required) and available (Boolean, default true) in the Book schema.
    const mongoose = require('mongoose');
    
    const bookSchema = new mongoose.Schema({
        title: { type: String, required: true },
        author: { type: String, required: true },
        publishedYear: { type: Number, required: true }, // Correction: use publishedYear
        genre: { type: String, required: true },
        available: { type: Boolean, default: true } // New field for availability
    });
    
    const Book = mongoose.model('Book', bookSchema);
    module.exports = Book;
  2. Added PATCH Route:

    • Registered the PATCH /books/:id route in /routes/bookRoutes.js, pointing to the patchBook method in the book controller.
    const express = require('express');
    const bookController = require('../controllers/bookController');
    const router = express.Router();
    
    router.post('/books', bookController.createBook);
    router.get('/books', bookController.getAllBooks);
    router.get('/books/search', bookController.searchBooks);
    router.get('/books/:id', bookController.getBookById);
    router.put('/books/:id', bookController.updateBook);
    router.patch('/books/:id', bookController.patchBook); // Add PATCH route for partial update
    router.delete('/books/:id', bookController.deleteBook);
    
    module.exports = router;
  3. Controller and Service Verification:

    • Verified that the existing patchBook method in /controllers/bookController.js and the corresponding service method in /services/bookService.js correctly handle the PATCH request as per the document specifications. No additional changes were necessary for these files.

Summary

  • The PATCH /books/:id endpoint will now update only the fields sent in the request body and validate the publishedYear field.
  • It returns the updated book object or relevant error codes (400/404) as needed.
  • No authentication is required for this endpoint as per the documentation.

Merge request reports