albatrosary's blog

UI/UXとエンタープライズシステム

NestJS でのバリデーション設定

  • ライブラリの登録
npm i class-validator, class-transformer -S
  • ValidationPipe有効化
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());

@UsePipes(new ValidationPipe()) を使ってメソッドごとの設定も可

  • DTO の作成
export class UserDto implements User {
  @IsString()
  readonly id: string;

  @IsString()
  readonly name: string;

  @IsNumber()
  readonly age: number;

  @IsString()
  @IsOptional()
  readonly organization: string;
}
  • 実行例
% curl -XPOST localhost:3000/api/v1/user -H "Content-Type: application/json" -d '{"id": "aa", "name": "aa", "age": "aaa"}'
{"statusCode":400,"message":["age must be a number conforming to the specified constraints"],"error":"Bad Request"}