[JITERA] Refactor deleteBook Function in Book Controller and Service
Created by: chi-jitera
Overview
This pull request refactors the deleteBook function in both the bookController.js and bookService.js files to enhance error handling and response structure. The changes ensure that the application adheres to best practices for separation of concerns and improves the overall maintainability of the code.
Changes
-
Controller:
bookController.js- Refactor deleteBook function: The function now includes improved error handling. If an error occurs during the deletion process, a 404 status code is returned along with a JSON object containing the error message.
exports.deleteBook = async (req, res) => { try { const message = await bookService.deleteBook(req.params.id); res.json(message); } catch (error) { res.status(404).json({ error: error.message }); } }; -
Service:
bookService.js- Refactor deleteBook function: The service layer now checks if the book exists before attempting to delete it. If the book is not found, an error is thrown with a descriptive message. This ensures that the controller can handle the error appropriately.
exports.deleteBook = async (bookId) => { const book = await Book.findByIdAndDelete(bookId); if (!book) throw new Error('Book not found'); return { message: 'Book deleted successfully' }; }; -
Model:
Book.js- No changes were made to the model, but it is included for reference. The schema remains unchanged and continues to define the structure of the book entity.
This refactoring enhances the robustness of the delete functionality and provides clearer feedback to the client when an operation fails.