Skip to content

[JITERA] Refactor Book Update Endpoint

chi le requested to merge feat/refactor-book-update-endpoint-1753807151 into main

Created by: chi-jitera

Overview

This pull request refactors the Book Update endpoint to align with the documented API specifications and improve error handling and validation. The changes ensure that the update flow is consistent and modular, following the structure: Route → Controller → Service → Mongoose Model.

Changes

  1. Route Definition:

    • Updated /routes/bookRoutes.js to define the PUT route for updating a book by ID. The updateBook controller is now properly imported and applied to the route.
    // /routes/bookRoutes.js
    const express = require('express');
    const router = express.Router();
    const bookController = require('../controllers/bookController'); 
    // PUT /books/:id - Update a book by ID
    router.put('/books/:id', bookController.updateBook); 
    module.exports = router;
  2. Controller Logic:

    • Refactored the updateBook controller in /controllers/bookController.js to extract parameters and body data, utilize the service for updating, check for book existence, and return appropriate error messages.
    // /controllers/bookController.js
    const bookService = require('../services/bookService'); 
    exports.updateBook = async (req, res) => { 
        const { id } = req.params; 
        const updateData = req.body; 
        try { 
            const updatedBook = await bookService.updateBook(id, updateData); 
            if (!updatedBook) { 
                return res.status(404).json({ error: 'Book not found' }); 
            } 
            return res.status(200).json(updatedBook); 
        } catch (err) { 
            if (err.name === 'ValidationError') { 
                return res.status(400).json({ error: err.message }); 
            } 
            return res.status(500).json({ error: 'Internal Server Error' }); 
        }
    };
  3. Service Layer:

    • Updated the updateBook service in /services/bookService.js to use Mongoose's findByIdAndUpdate method with validation, ensuring that only existing books are updated.
    // /services/bookService.js
    const Book = require('../models/Book'); 
    exports.updateBook = async (id, updateData) => { 
        const options = { new: true, runValidators: true }; 
        const updatedBook = await Book.findByIdAndUpdate(id, updateData, options).lean(); 
        return updatedBook;
    };
  4. Mongoose Model:

    • Ensured that the schema in /models/Book.js matches the documented fields and maintains compatibility with update operations.
    // /models/Book.js
    const mongoose = require('mongoose'); 
    const bookSchema = new mongoose.Schema({ 
        title: { type: String, required: true }, 
        author: String, 
        publishedDate: Date, 
        genre: String 
    }); 
    module.exports = mongoose.model('Book', bookSchema);

Summary

  • The refactor adheres to the documented API flow and conventions.
  • It ensures that only provided fields in the request body are updated.
  • The endpoint now returns appropriate HTTP status codes: 200 for success, 404 for not found, and 400 for validation errors.
  • All code changes are modular and maintain the project's coding style.

Merge request reports