nestjs-cqrs-extra
v1.1.8
Published
Library that provides additional features for the NestJS CQRS module.
Downloads
14
Maintainers
Readme
About
Nest CQRS Extra is a module that provides additional features for the NestJS CQRS module. It provides a way to send commands and queries through a message broker (e.g. NATS, Redis, MQTT) to the appropriate handlers in microservices. It also provides a way to create sagas that can be used to handle events.
Features
- Typings - Provides typings for commands, queries, and events. (Request & Response)
- Message Broker - Provides a way to send commands and queries to the appropriate handlers in microservices.
- Saga - Provides a way to create sagas that can be used to handle events.
Installation
$ npm install nestjs-cqrs-extra @nestjs/microservices nats
Usage
Import the module
import { Module } from '@nestjs/common';
import { CqrsModule } from 'nestjs-cqrs-extra';
@Module({
imports: [
CqrsModule.forRoot({
options: { servers: ['nats://localhost:4222'] }
})
]
})
export class AppModule {
}
You can change adapter to redis
or mqtt
by changing the adapter
option.
Create a command
import { BaseCommand } from 'nestjs-cqrs-extra';
export class CreateUserCommand extends BaseCommand<string> {
constructor(public readonly name: string) {
super();
}
}
Create a command handler
import { CommandHandler } from 'nestjs-cqrs-extra';
import { CreateUserCommand } from './create-user.command';
import { Controller } from '@nestjs/common';
@Controller()
export class UserCommandsController {
@CommandHandler(CreateUserCommand)
public createUser(command: CreateUserCommand): string {
return `User ${command.name} created`;
}
}
Also you can use @QueryHandler
and @EventHandler
decorators to handle queries and events.
Send a command
import { CommandBus } from 'nestjs-cqrs-extra';
import { Injectable } from '@nestjs/common';
@Injectable()
export class UserService {
constructor(private readonly commandBus: CommandBus) {
}
async createUser(name: string): Promise<string> {
return this.commandBus.execute(new CreateUserCommand(name));
}
}
Stay in touch
- Author - Alexey Filippov
- Twitter - @SocketSomeone