I try to use a command DTO but his handler is not recognized.
When I log the DTO, it is a simple object {...}
without CreateUserCommand
signature.
Here is my controller :
async index(@Body() createUserCommand: CreateUserCommand): Promise<User> {
console.log(createUserCommand);
return await this.commandBus.execute(createUserCommand);
}
I get the following output :
{
firstName: 'xxx',
lastName: 'xxx',
email: 'xxx@xxx.com',
password: 'xxx'
}
When i try to use directly the command it is working :
const command = new CreateUserCommand();
command.firstName = 'xxx';
command.lastName = 'xxx';
command.email = 'xxx@xxx.com';
command.password = 'xxx';
return await this.commandBus.execute(createUserCommand);
The following output :
CreateUserCommand {
firstName: 'xxx',
lastName: 'xxx',
email: 'xxx@xxx.com',
password: 'xxx'
}
Is it possible to use a DTO as a command handler?
If you use @Body
it will produce a plain javascript object but not an instance of your dto class. You can use class-transformer
and its plainToClass(CreateUserCommand, createUserCommand)
method to actually create an instance of your class.
If you are using the ValidationPipe
it can automatically transform your plain object to a class if you pass the option transform: true
:
@UsePipes(new ValidationPipe({ transform: true }))
async index(@Body() createUserCommand: CreateUserCommand): Promise<User> {
console.log(createUserCommand);
return await this.commandBus.execute(createUserCommand);
}