In this article, we will implement the CQRS Design Pattern in the NestJS sample application.
CQRS:
CQRS stands for Command Query Responsibility Segregation. CQRS guides us to separate our logical implementation into 2 categories like 'Command', 'Query'. The 'Commands' specifies the operation like creation or updating of data into the data source(database). The 'Query' specifies the operations to fetch the data.
PostgreSQL Database:
For this demo, I'm using the free open-source PostgreSQL database. Here I'm going to use the PostgreSQL docker image because it is easy and fast to set up and configure. Click here to getting started with PostgreSQL docker.
Run the below command to create an example table for a demo like 'Person'.
CREATE TABLE Person( Id SERIAL PRIMARY KEY NOT NULL, Name Text NULL, Age INT NULL )
Create A NestJS Application:
Let's begin our demo by creating a sample NestJS application.
Command To Install NestJS CLI
npm i -g @nestjs/cli
npm i -g @nestjs/cli
Command To Create NestJS APP
nest new your_project_name
nest new your_project_name
Initial Setup:
Let's install the ORM packages for the database communication.
Install NestJS Type ORM
npm install --save @nestjs/typeorm
npm install --save @nestjs/typeorm
Install NodeJS Type ORM
npm install --save typeorm
npm install --save typeorm
Install NodeJS PostgreSQL
npm install --save pg
npm install --save pg
Now let's create a class that represents our 'Person' table, so add these classes into folders like 'entities'.
Run the below command to generate our table class.
nest g cl entities/person --no-spec
src/entities/person.ts:
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'; @Entity({name:'person'}) export class Person { @PrimaryGeneratedColumn('increment',{name:'id'}) id: number; @Column({name:'name'}) name: string; @Column({name:'age'}) age: number; }Now let's configure the database settings in the 'app.module.ts'.
src/app.module.ts:
import { TypeOrmModule } from '@nestjs/typeorm'; import { Person } from './entities/person'; @Module({ imports: [ TypeOrmModule.forRoot({ type:'postgres', host:'localhost', port: 5432, username: 'postgres', password:'secret', database:'myworlddb', entities:[Person] }) ] }) export class AppModule {}
- (Line: 13) Need to register our table classes with in the 'entities' array.
nest g mo person
Now let's create a 'person.controller.ts', so lets run the below command.
nest g co person --no-spec
Now update the 'person.module.ts' by registering the 'TypeOrmModule.feature()'.
src/person/person.module.ts:
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Person } from 'src/entities/person'; import { PersonController } from './person.controller'; @Module({ imports:[TypeOrmModule.forFeature([Person])], controllers: [PersonController] }) export class PersonModule {}
Install And Configure CQRS NestJS Package:
Let's first install the CQRS NestJS package, so run the below command.
npm install --save @nestjs/cqrs
Now register the 'CqrsModule' in 'person.modulet.ts'.
src/person/person.module.ts:
import { CqrsModule } from '@nestjs/cqrs'; // code hidden for display purpose @Module({ imports:[CqrsModule] }) export class PersonModule {}
- Here imported 'CqrsModule' that loads from the '@nestjs/cqrs'.
Implement CQRS QueryHandler:
The QueryHandler is a class that contains logic to fetch the data from the data source. So to implement the CQRS query 2 main things we need are like 'Implementation Model(or Request Model)', 'Query Handler'.
So let's create 'Implementation Model(or Request Model)', this model will be implemented by the 'QueryHandler' that tells us a story like one 'Implementation Model' is designated to one 'QueryHandler'. In the controller, we will instantiate our 'Implementation Model' it will automatically involve the respective 'QueryHandler' that implements it. So let's create an 'Implementation Model' file like 'src/person/queries/impl/get-persons.query.ts'.
nest g cl person/queries/impl/get-persons.query --no-spec
src/person/queries/impl/get-persons.query.ts:
export class GetPersonsQuery {}
- The 'GetPersonsQuery' is our 'Implementation Model'. Here is one more interesting thing we can observe my class is totally empty, so in case if we have any query params then we have to add properties for them into our 'Implementation Model'.
nest g cl person/queries/handlers/get-persons.handler --no-spec
src/person/queries/handlers/get-persons.handler.ts:
import { IQueryHandler, QueryHandler } from '@nestjs/cqrs'; import { InjectRepository } from '@nestjs/typeorm'; import { Person } from 'src/entities/person'; import { Repository } from 'typeorm'; import { GetPersonsQuery } from '../impl/get-persons.query'; @QueryHandler(GetPersonsQuery) export class GetPersonsHandler implements IQueryHandler<GetPersonsQuery> { constructor( @InjectRepository(Person) private personRepo: Repository<Person>, ) {} async execute(query: GetPersonsQuery): Promise<Person[]> { return await this.personRepo.find(); } }
- (Line: 7) Our handler must register with a decorator like '@QueryHandler' that loads from the '@nestjs/cqrs'.
- (Line: 8) Our handler class need to implement 'IQueryHandler<TRequestModel>'.
- (Line: 9-11) Inject our 'Person' table entity repository that provides default methods to interact with the database.
- (Line: 12) The 'excute' method gots auto executed on invocation of our handler and to this method, our 'Implementation Model(or Request Model)' will by the input parameter.
- (Line: 13) Fetching all records from the database.
src/person/person.module.ts:
import { GetPersonsHandler } from './queries/handlers/get-persons.handler'; // code hidden for display purpose @Module({ providers:[GetPersonsHandler] }) export class PersonModule {}Now let's create an endpoint that invokes our QueryHandler.
src/person/person.controller.ts:
import { Controller, Get } from '@nestjs/common'; import { QueryBus } from '@nestjs/cqrs'; import { GetPersonsQuery } from './queries/impl/get-persons.query'; @Controller('person') export class PersonController { constructor(private readonly queryBus: QueryBus) {} @Get('all') async getAll() { return await this.queryBus.execute(new GetPersonsQuery()); } }
- (Line: 7) Inject the 'QueryBus' instance that loads from the '@nestjs/cqrs'.
- (Line: 11) Pass the instance of our 'Implementation Model' that is 'GatPersonQuery' as input to the execute method of the 'QueryBus' that will implicitly invoke our 'QueryHandler'.
Implement CQRS CommandHandler:
The CommandHandler is a class that contains logic to save data into the data source. So to implement the CQRS command 2 main things we need are like 'Implementation Model(or Request Model)', 'Command Handler'.
So let's create 'Implementation Model(or Request Model)', this model will be implemented by the 'CommandHandler' that tells us a story like one 'Implementation Model' is designated to one 'CommandHandler'. In the controller, we will instantiate our 'Implementation Model' it will automatically involve the respective 'CommandHandler' that implements it. So let's create an 'Implementation Model' file like 'src/person/commands/impl/save-person.command.ts'.
nest g cl person/commands/impl/save-person.command --no-spec
src/person/commands/impl/save-person.commands.ts:
export class SavePersonCommand { name: string; age: number; }
- The 'SavePersonCommand' is our 'Implementation Model' which is also our payload model for API endpoint.
nest g cl person/commands/handler/save-person.handler --no-spec
src/person/commands/handler/save-person.handler.ts:
import { CommandHandler, ICommandHandler } from "@nestjs/cqrs"; import { InjectRepository } from "@nestjs/typeorm"; import { Person } from "src/entities/person"; import { Repository } from "typeorm"; import { SavePersonCommand } from "../impl/save-person.command"; @CommandHandler(SavePersonCommand) export class SavePersonHandler implements ICommandHandler<SavePersonCommand> { constructor( @InjectRepository(Person) private personRepo: Repository<Person>, ) {} async execute(command: SavePersonCommand) { var person = new Person(); person.age = command.age; person.name = command.name; await this.personRepo.insert(person); } }
- (Line: 7) The 'SavePersonHandler' is decorated with '@CommandHandler' that loads from '@nestjs/cqrs'.
- (Line: 8) Our Command Handler should implement 'ICommandHandler<TRequestModel>'.
- (Line: 13-18) Saving a new record into the database.
Now register our 'SavePersonHandler'(command handler) into the 'person.module.ts'.
src/person/person.module.ts:
import { SavePersonHandler } from './commands/handler/save-person.handler'; // code hidden for display purpose @Module({ providers:[SavePersonHandler] }) export class PersonModule {}Now let's create a save endpoint.
src/person/person.controller.ts:
import { Body, Controller, HttpCode, Post } from '@nestjs/common'; import { CommandBus } from '@nestjs/cqrs'; import { SavePersonCommand } from './commands/impl/save-person.command'; //code hidden for display purpose @Controller('person') export class PersonController { constructor(private readonly commandBus:CommandBus) {} @Post('add') @HttpCode(201) async createEmployee(@Body() newPerson: SavePersonCommand) { return await this.commandBus.execute(newPerson); } }
- (Line: 7) Injected 'CommandBus' that loads from '@nestjs/cqrs'
- (Line: 9-13) Save action method, invoking the command handler from the 'CommandBus.execute()'.
The reason behind the above error is in our save action method input parameter is like '@Body() newPerson: SavePersonCommand' so on receiving request 'newPerson' variable captures the payload as a javascript object but our CommandBus expects class type. So to fix this we have to install the below libraries.
npm install class-transformer
npm install class-validator
Now update action method as below:
@Post('add') @HttpCode(201) @UsePipes(new ValidationPipe({ transform: true })) async createEmployee(@Body() newPerson: SavePersonCommand) { return await this.commandBus.execute(newPerson); }
- (Line: 3) The 'ValidationPipe({transform:true})' helps to make our action input parameter as the class object instead of javascript object.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on the CQRS Design Pattern implementation in the NestJS application. I love to have your feedback, suggestions, and better techniques in the comment section below.
This comment has been removed by the author.
ReplyDeleteWhat exactly commandbus will do and event bus will do
ReplyDeleteI would like to know about commandbus and eventbus
ReplyDeleteThanks a lot for neat and clean explanation
ReplyDeleteWow great, the explanation step by step, but I have a question, all the code is in the microservice, right? If I had an api-gateway architecture, what changes would I have to make?
ReplyDelete