Deleting A Book Listing By ID - Implementation

1 - Route Name

This will be our final API endpoint!

DELETE /api/v1/books/:id

Just like we planned, let's add in the route and our controller.

File: src/routes/book.route.js

const express = require('express')
const router = 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 in
router.delete('/:id', deleteABook)

File: src/controllers/book/deleteABook.js

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.

File: src/routes/book.route.js

4 - Validation

None.

5 - Domain

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

File: src/domain/services/book.service.js

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.

Last updated