Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class-validator doesn't validate arrays

I can't get the class-validator to work. It seems like I am not using it: everything works as if I didn't use class-validator. When sending a request with an incorrectly formatted body, I don't have any validation error, although I should.

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

My controller:

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

My bootstrap:

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

I can't find what's wrong. What did I miss?

like image 561
papillon Avatar asked Jan 21 '20 10:01

papillon


1 Answers

In the current version of NestJS (7.6.14), validating a request body that is a JSON array is supported using the built in ParseArrayPipe.

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

See the official docs or the source code for more info.

like image 71
thomaux Avatar answered Oct 13 '22 02:10

thomaux