关于nestjs:NestJS-校验数据类型

记录当NestJSbody申请体是数组对象时,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:

success

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理