pap*_*lon 5 arrays validation class-validator nestjs
我无法让类验证器工作。似乎我没有使用它:一切正常,就好像我没有使用类验证器一样。当发送带有格式不正确正文的请求时,我没有任何验证错误,尽管我应该。
我的 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;
}
Run Code Online (Sandbox Code Playgroud)
我的控制器:
@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);
}
Run Code Online (Sandbox Code Playgroud)
我的引导程序:
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();
Run Code Online (Sandbox Code Playgroud)
我找不到问题所在。我错过了什么?
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[];
}
Run Code Online (Sandbox Code Playgroud)
我会在我的控制器中使用该 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);
}
Run Code Online (Sandbox Code Playgroud)