【问题标题】:Validation by class-validator or class-transformer dont work when apply multiple Types on @Query docrator在@Query docrator 上应用多个类型时,类验证器或类转换器的验证不起作用
【发布时间】:2022-01-17 00:08:04
【问题描述】:

我想在 @Query() 装饰器中组合多种类型(例如 ParamsWithRegex 和 PaginationParams),但是当我这样做时没有应用验证,如何解决这个问题?


 **// MY CONTROLLER : here I combine two types but validate didnt work**
 @Get()
  async findAll(
    @Query() query: PaginationParams & ParamsWithRegex,
  ) {
    return 'OK'
  }



// ParamsWithRegex.dto.ts
export class ParamsWithRegex {
  @IsOptional()
  @Transform(({ obj }) => {
    return new RegExp(escapeRegExp(obj.name), 'i');
  })
  name?: string;
}





// paginationParams.dto.ts 
export class PaginationParams {
  @IsOptional()
  @Type(() => Number)
  @IsNumber()
  @Min(1)
  page?: number = 1;

  @IsOptional()
  @Type(() => Number)
  @IsNumber()
  @Min(1)
  limit?: number = 8;
}

【问题讨论】:

    标签: node.js typescript nestjs


    【解决方案1】:

    您可以使用Mapped-Types 创建您的 Dto:

    @Get()
    async findAll(@Query() query: CombinedDto) {
      ...
    }
    
    export class CombinedDto extends IntersectionType(
      ParamsWithRegex,
      PaginationParams
    ) {}
    

    【讨论】:

      猜你喜欢
      • 2020-05-20
      • 2022-01-17
      • 2013-04-19
      • 1970-01-01
      • 2013-01-02
      • 2020-09-10
      • 2020-07-08
      • 2022-09-23
      • 2021-02-23
      相关资源
      最近更新 更多