Updating A Book Listing By ID - Implementation
1 - Route Name
PUT /api/v1/books/:id
Just like we planned, let's add in the route.
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)
// This is the new route we are adding in
router.put('/:id', updateABook)Let's also create our controller so we can fill in the details later on.
File: src/controllers/book/updateABook.js
2 - Input Request
For the input request, this will seem very familiar. It's because this is the exact code we used for our createBookRequestDto.js with the exception of an additional id field.
File: src/controllers/requests/updateBookRequestDto.js
3 - Middleware
File: src/routes/book.route.js
As stated previously, we need a way to check if the request book to be updated does indeed belong to the currently authenticated user.
This will help us do so. Notice also that we are going to be using the bookService.getBookId method we created previously. This is a great functionality to reuse because the getBookById inherently has a check to see if the bookId is correct, otherwise it will throw an exception.
File: src/middleware/bookPermission.middleware.js
4 - Validation
Again, this is very similar to the createBookValidator with the exception of an additional id field. You are probably wondering why we require all fields instead of a subset of them. Do recall that this is a PUT request, which means we must accept the entire resource into our API as we are re-updating the entire entity in database.
File: src/validators/updateBookValidator.js
5 - Domain
Yet again, this is similar to what we had before when we wrote the create method in our bookRepository and the createBook method in our bookService. We now do this for updating a book.
File: src/domain/repositories/book.repository.js
File: src/domain/services/book.service.js
6 - Events
None.
7 - Response
Now for the response.
Do note that our isAuthenticated and bookPermission middleware will handle most of the error messages for us.
For our success message we will put have the following in our controller.
File: src/controllers/book/updateABook.js
Once again, this is nice and thin, and easy on the eyes.
Last updated