javascript - 找不到带有命令负载的 CommandHandler 异常
我尝试使用一个命令 DTO,但它的处理程序未被识别。当我记录 DTO 时,它是一个简单的对象 {...},没有 CreateUserCommand 的特征。
这是我的控制器:
async index(@Body() createUserCommand: CreateUserCommand): Promise<User> {
console.log(createUserCommand);
return await this.commandBus.execute(createUserCommand);
}
我得到以下输出:
{
firstName: 'xxx',
lastName: 'xxx',
email: '[email ',
password: 'xxx'
}
当我尝试直接使用命令时,它是可行的:
const command = new CreateUserCommand();
command.firstName = 'xxx';
command.lastName = 'xxx';
command.email = '[email ';
command.password = 'xxx';
return await this.commandBus.execute(createUserCommand);
以下输出:
CreateUserCommand {
firstName: 'xxx',
lastName: 'xxx',
email: '[email ',
password: 'xxx'
}
可以将 DTO 用作命令处理器吗?
答案#1
如果你使用 @Body,它会生成一个普通的 JavaScript 对象,而不是你的 DTO 类的实例。你可以使用 class-transformer 及其 plainToClass(CreateUserCommand, createUserCommand) 方法来实际创建你的类的实例。
如果你使用 ValidationPipe,如果你传入选项 transform: true,它可以自动将你的普通对象转换为一个类:
@UsePipes(new ValidationPipe({ transform: true }))
async index(@Body() createUserCommand: CreateUserCommand): Promise<User> {
console.log(createUserCommand);
return await this.commandBus.execute(createUserCommand);
}
