【问题标题】:class-validator doesn't validate arrays类验证器不验证数组
【发布时间】:2020-05-07 08:47:53
【问题描述】:

我无法让类验证器工作。好像我没有使用它:一切正常,就好像我没有使用类验证器一样。当发送一个格式不正确的请求时,我没有任何验证错误,虽然我应该。

我的 DTO:

import { IsInt, Min, Max } from 'class-validator';

export class PatchForecastDTO {
  @IsInt()
  @Min(0)
  @Max(9)
  score1: number;

  @IsInt()
  @Min(0)
  @Max(9)
  score2: number;
  gameId: string;
}

我的控制器:

@Patch('/:encid/forecasts/updateAll')
async updateForecast(
    @Body() patchForecastDTO: PatchForecastDTO[],
    @Param('encid') encid: string,
    @Query('userId') userId: string
): Promise<ForecastDTO[]> {
  return await this.instanceService.updateForecasts(userId, encid, patchForecastDTO);
}

我的引导程序:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(PORT);
  Logger.log(`Application is running on http://localhost:${PORT}`, 'Bootstrap');
}
bootstrap();

我找不到问题所在。我错过了什么?

【问题讨论】:

标签: arrays validation nestjs class-validator


【解决方案1】:

NestJS 实际上是does not support array validation out of the box。为了验证一个数组,它必须被包装在一个对象中。

这样,我不会使用对应于项目列表的 DTO,而是使用对应于包含项目列表的对象的 DTO:

import { PatchForecastDTO } from './patch.forecast.dto';
import { IsArray, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';

export class PatchForecastsDTO {
    @IsArray()
    @ValidateNested() // perform validation on children too
    @Type(() => PatchForecastDTO) // cast the payload to the correct DTO type
    forecasts: PatchForecastDTO[];
}

我会在我的控制器中使用该 DTO:

@Patch('/:encid/forecasts/updateAll')
async updateForecast(
    @Body() patchForecastsDTO: PatchForecastsDTO,
    @Param('encid') encid: string,
    @Query('userId') userId: string
): Promise<ForecastDTO[]> {
  return await this.instanceService.updateForecasts(userId, encid, patchForecastsDTO);
}

【讨论】:

    【解决方案2】:

    在当前版本的 NestJS (7.6.14) 中,支持使用内置的 ParseArrayPipe 验证作为 JSON 数组的请求正文。

    @Post()
    createBulk(
      @Body(new ParseArrayPipe({ items: CreateUserDto }))
      createUserDtos: CreateUserDto[],
    ) {
      return 'This action adds new users';
    }
    

    请参阅official docssource code 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2018-08-21
      • 2021-02-03
      • 2021-07-24
      • 2021-03-09
      • 2020-07-30
      • 2022-10-31
      • 2022-12-11
      • 1970-01-01
      • 2020-05-20
      相关资源
      最近更新 更多