Creating A Book Listing - Implementation

1 - Route Name

POST /api/v1/books

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 } = require('../controllers/book')

router.get('/', getAllBooks)
router.get('/:id', getBookById)

// This is the new route we are adding in
router.post('/', createABook)

Let's also create our controller so we can fill in the details later on.

File: src/controllers/book/createABook.js

const catchException = require('../../utils/catchExceptions')

/**
 * Creates a new book listing.
 */
const createABook = catchException(async (req, res) => {
  // we'll fill in the details after we get each of the other layers ready
})

module.exports = createABook

2 - Input Request

Very similar to how we implemented our registerUserRequestDto, we'll create a createBookRequestDto that has the fields title, description, price, author, and datePublished in it.

File: src/requests/createBookRequestDto.js

3 - Middleware

We are going to be reusing the isAuthenticated middleware from before and add it in right before our controller.

File: src/routes/book.route.js

4 - Validation

Let's not forget about the validation layer. Again, this is very similar to the registerUserValiator function we created in the previous chapter except it's just going to be for different fields.

File: src/validators/createBookValidator.js

5 - Domain

As mentioned in the previous planning section, this will be the model we create.

File: src/domain/models/book.model.js

This will be the repository layer on top of that model.

File: src/domain/repositories/book.repository.js

Finally, our service layer that will use the bookRepository layer.

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

6 - Events

None.

7 - Response

If we put this all together now in the controller, this is what we'll get.

The createBookRequestDto and the createBookValidator will naturally throw an ApiException which will yield the correct output response as we stated previously in the planning section of this endpoint.

In case of no errors and we get a successful pass, we will reuse our bookResponseDto from which we created previously on the output of the bookService.create method we just implemented and return the newly created book in our response.

Last updated