类验证器不验证数组 [英] class-validator doesn't validate arrays

查看:20
本文介绍了类验证器不验证数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法让类验证器工作。看起来我没有使用它:一切都像我没有使用类验证器一样工作。发送正文格式不正确的请求时,我没有任何验证错误,尽管我应该出错。

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

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

推荐答案

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);
}

这篇关于类验证器不验证数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆