CommandHandler未找到命令有效内容的异常

问题描述 投票:1回答:1

我尝试使用命令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 protected]',
    password: 'xxx'
}

当我尝试直接使用它正在工作的命令时:

const command = new CreateUserCommand();
command.firstName = 'xxx';
command.lastName = 'xxx';
command.email = '[email protected]';
command.password = 'xxx';

return await this.commandBus.execute(createUserCommand);

以下输出:

 CreateUserCommand { 
    firstName: 'xxx',
    lastName: 'xxx',
    email: '[email protected]',
    password: 'xxx'
}

是否可以使用DTO作为命令处理程序?

javascript node.js typescript nestjs class-transformer
1个回答
0
投票

如果使用@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);
}
© www.soinside.com 2019 - 2024. All rights reserved.