Just like we planned, let's add in the route and our controller.
File: src/routes/book.route.js
constexpress=require('express')constrouter=express.Router()const {getAllBooks,getBookById,createABook,updateABook} =require('../controllers/book')router.get('/', getAllBooks)router.get('/:id', getBookById)router.post('/', createABook)router.put('/:id', updateABook)// This is the new route we are adding inrouter.delete('/:id', deleteABook)
File: src/controllers/book/deleteABook.js
constcatchException=require('../../utils/catchExceptions')/** * Deletes an existing new book listing. */constdeleteABook=catchException(async (req, res) => {// Our code goes here})
2 - Input Request
None.
3 - Middleware
As mentioned before, we will be reusing our isAuthenticated and bookPermission middleware.
If we plug those in, our route should look something like this.
If you've followed along till this point, then the following will be of no surprise to you. Do note that because we are deleting a book, the deleteOne method from mongoose will either return a 1 for successful deletion or a 0 for a failed deletion. For a failed deletion to happen, it will have been an invalid bookId was inputted. Recall that we have already taken care of that in our bookPermission middleware, so no error handling is necessary here.
File: src/domain/repositories/book.repository.js
constModel=require('../models/book.model')// DeleteconstdeleteById=async (id) => {returnawaitModel.deleteOne({ _id: id })}module.exports= { deleteById}
File: src/domain/services/book.service.js
constmongoose=require('mongoose')constApiException=require('../../utils/ApiException')constbookRepository=require('../repositories/book.repository')constcheckBookId=require('../../utils/checkBookId')// Delete a bookconstdeleteBookById=async (bookId) => {returnawaitbookRepository.deleteById(bookId)}module.exports= { deleteBookById}
6 - Events
None.
7 - Response
Once all our error handling will be taken care of by the isAuthenticated and bookPermission middleware. If there are no errors, we should show a success message like the following.
constglobalResponseDto=require('../../responses/globalResponseDto')constcatchException=require('../../utils/catchExceptions')constbookService=require('../../domain/services/book.service')/** * Deletes an existing new book listing. */constdeleteABook=catchException(async (req, res) => {constbook=awaitbookService.deleteBookById(req.params.id)res.json(globalResponseDto({ status:'success', code:200, message:`The book with the id: ${book.id} was successfully deleted.`, data:null, errors:null }) )})module.exports= deleteABook