gpt4 book ai didi

javascript - CommandHandler 未找到命令负载异常

转载 作者:行者123 更新时间:2023-11-30 19:39:30 25 4
gpt4 key购买 nike

我尝试使用命令 DTO,但无法识别他的处理程序。当我记录 DTO 时,它是一个没有 CreateUserCommand 签名的简单对象 {...}

这是我的 Controller :

async index(@Body() createUserCommand: CreateUserCommand): Promise<User> {
console.log(createUserCommand);
return await this.commandBus.execute(createUserCommand);
}

我得到以下输出:

 { 
firstName: 'xxx',
lastName: 'xxx',
email: 'xxx@xxx.com',
password: 'xxx'
}

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

const command = new CreateUserCommand();
command.firstName = 'xxx';
command.lastName = 'xxx';
command.email = 'xxx@xxx.com';
command.password = 'xxx';

return await this.commandBus.execute(createUserCommand);

以下输出:

 CreateUserCommand { 
firstName: 'xxx',
lastName: 'xxx',
email: 'xxx@xxx.com',
password: 'xxx'
}

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

最佳答案

如果您使用 @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);
}

关于javascript - CommandHandler 未找到命令负载异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55557054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com