【问题标题】:CommandHandler not found exception with command payloadCommandHandler 未发现命令有效负载异常
【发布时间】:2019-08-28 15:16:23
【问题描述】:

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

这是我的控制器:

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 用作命令处理程序?

【问题讨论】:

    标签: javascript node.js typescript nestjs class-transformer


    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 2014-06-21
      • 2018-12-09
      相关资源
      最近更新 更多