6

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

我的 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();

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

4

2 回答 2

4

在当前版本的 NestJS (7.6.14) 中,支持使用内置的ParseArrayPipe.

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

有关更多信息,请参阅官方文档源代码

于 2021-03-15T09:04:55.960 回答
3

NestJS 实际上不支持开箱即用的数组验证。为了验证一个数组,它必须被包装在一个对象中。

这样,我不会使用对应于项目列表的 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);
}
于 2020-01-21T14:23:25.873 回答