[JITERA] Implement PATCH /books/:id for partial updates to book records
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 ensures that only the fields provided in the request body are updated, adhering to the specifications outlined in the API documentation.
Changes Made
-
Updated Book Model:
- Modified
/models/book.jsto include the missing fieldspublishedYear(Number, required) andavailable(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; - Modified
-
Added PATCH Route:
- Registered the
PATCH /books/:idroute in/routes/bookRoutes.js, pointing to thepatchBookmethod 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); // Add PATCH route for partial update router.patch('/books/:id', bookController.patchBook); router.delete('/books/:id', bookController.deleteBook); module.exports = router; - Registered the
-
Controller and Service Verification:
- Verified that the existing
patchBookmethod in/controllers/bookController.jsand the corresponding service method in/services/bookService.jscorrectly handle the PATCH request as per the document specifications. No additional changes were necessary for these files.
- Verified that the existing
Summary
- The
PATCH /books/:idendpoint now allows for partial updates to book records, updating only the fields sent in the request body. - The implementation includes validation for the
publishedYearfield and returns the updated book object or relevant error codes (400/404) as needed. - No authentication is required for this endpoint as per the documentation.