NestJS 校验数据类型

记录当NestJS的body请求体是数组对象时,dto的使用:

dto.ts:

import { IsNumber, Min, IsNotEmpty, IsOptional, IsString } from 'class-validator';

export class UserDto {
  @IsNotEmpty()
  @IsString()
  readonly name!: string;

  @IsNotEmpty()
  @IsNumber()
  @Min(0)
  readonly age!: number;

  @IsNotEmpty()
  @IsString()
  readonly city!: string;

  @IsOptional()
  @IsString()
  readonly description?: string;
}

controller.ts

import {  UserDto } from "./dto";
import {
  Controller,
  Post,
  Body,
  ParseArrayPipe
} from "@nestjs/common";

@Controller("/")
export class TestController {

 @Post("test/dto")
  public async userInfo(
    @Body(
      new ParseArrayPipe({
        items: UserDto,
      }))
    data: UserDto[]
  ) {
    return 'request success'
  }
} 

效果:
error:
image.png

success
image.png

评论

暂无评论