For the route version prefix, we can do the following.
File: src/server.js
constgetRouter=require('./routes')constrouter=getRouter()app.use('/api/v1', router) // add the prefix '/api/v1' to all our URIs
We will then proceed to include all of the book routes.
File: src/routes/index.js
constexpress=require('express')constrouter=express.Router()constbookRoutes=require('./book.route') // all our book routesfunctiongetRouter() {router.use('/books', bookRoutes) // we prefix it here as 'books'return router}module.exports= getRouter
Here, we specify and create a controller method, let's call it getAllBooks.
Now that all the setup is done, we can proceed with the other layers in our application.
2 - Input Request
None.
3 - Middleware
None.
4 - Validation
None.
5 - Domain
The domain layer is quite simple, we want to first create a model that satisfies all our business requirements from the user stories we have in the previous chapter. We are going to create the book model as follows.
Then, we will wrap it in a repository. Remember why we are using repositories, we want to be able to create an abstraction layer between the concrete implementation of the model and our service layer so that we may swap out database types any time we want. In our case, we are using MongoDB. If for some reason in the future we decide to use something like MySQL, PostgresQL, or OracleDB, it would be much easier to swap out.
constbookRepository=require('../repositories/book.repository')constApiException=require('../../utils/ApiException')constmongoose=require('mongoose')// Retrieve - all booksconstgetAllBooks=async () => {returnbookRepository.getAll()}module.exports= { getAllBooks}
6 - Events
None.
7 - Response
Here is what we will do to our controller in order to return a list of books
File: src/controllers/book.controller.js
constglobalResponseDto=require('../../responses/globalResponseDto')constbooksResponseDto=require('../../responses/booksResponseDto')constcatchException=require('../../utils/catchExceptions')constbookService=require('../../domain/services/book.service')/** * Gets all book listings from the database. */constgetAllBooks=catchException(async (req, res) => {constbooks=awaitbookService.getAllBooks()res.json(globalResponseDto({ status:'success', code:200, message:`List of all books in the database.`, data:booksResponseDto(books), errors:null }) )})module.exports= getAllBooks