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

4

1 回答 1

2

如果您使用@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);
}
于 2019-04-07T08:54:37.050 回答