首页 > 解决方案 > 一起使用两个 dto 类时不发送错误消息

问题描述

我有一个范围 dto 类:

export class UpdateProgramScopeDto {
  @Matches(scopeTypeRegex)
  @ApiProperty({
    type: String,
    description: 'scopeType',
    enum: SCOPE_TYPE,
  })
  scopeType: SCOPE_TYPE;
} 

以及在另一个类中使用它:

export class RegisterProgramDto {
  @IsArray()
  @ValidateNested({ message: 'd' })
  @Type(() => UpdateProgramScopeDto)
  @ApiProperty({
    type: UpdateProgramScopeDto,
    description: 'scopes',
    isArray: true,
  })
  scopes: UpdateProgramScopeDto[];
}

但是未发送范围类的错误消息我该如何解决?

@Post()
  async registerProgram(
    @Body(ValidationPipe) registerProgramDto: RegisterProgramDto,
    @User() user: AuthEntity,
  ) {
    return await this._programService.registerProgram(
      user.user_id,
      registerProgramDto,
    );
  }

标签: node.jsnestjs

解决方案


如果需要验证对象数组,请使用each: truein @ValidateNested({ each: true })

在 NestJS 中,您还需要Typefrom class-transform。这是一个工作示例:

export class Foo {
  @ValidateNested({ each: true })
  @Type(() => Bar)
  posts: Bar[];
}

推荐阅读