Skip to content

灵活使用 DTO

PartialType

  • 我们创建数据的时候,创建了一个 DTO,写好了属性,但是更新的时候我们没必要在重新写一遍 DTO,所以我们可以使用 PartialType

创建 create-aaa.dto

ts
import {
  IsBoolean,
  IsEmail,
  IsNotEmpty,
  IsNumber,
  Length,
  MaxLength,
  MinLength,
} from "class-validator";
export class CreateAaaDto {
  @IsNotEmpty()
  @MinLength(4)
  @MaxLength(20)
  name: string;

  @IsNotEmpty()
  @IsNumber()
  age: number;

  @IsNotEmpty()
  @IsBoolean()
  sex: boolean;

  @IsNotEmpty()
  @IsEmail()
  email: string;

  hobbies: string[];
}

更新 update-aaa.dto

ts
import { PartialType } from "@nestjs/mapped-types";
import { CreateAaaDto } from "./create-aaa.dto";

export class UpdateAaaDto extends PartialType(CreateAaaDto) {}

使用

  • 发送数据的时候,只需要发送需要更新的字段即可
ts
POST http://127.0.0.1:5000/aaa/45
Content-Type: application/json

{
    "age": 20,
    "email": "xxxx@xxx.com"
}

PickType

是必须填写字段

update-aaa.dto

ts
import { PickType } from "@nestjs/mapped-types";
import { CreateAaaDto } from "./create-aaa.dto";

export class UpdateAaaDto extends PickType(CreateAaaDto, ["name", "sex"]) {}

使用

  • name, sex 必须填写
ts
POST http://127.0.0.1:5000/aaa/45
Content-Type: application/json

{
    "name": "aaaaaaaa",
    "sex":true
}

OmitType

  • 忽略字段.剩余必须传,写的字段可以不用传

update-aaa.dto

ts
import { OmitType } from "@nestjs/mapped-types";
import { CreateAaaDto } from "./create-aaa.dto";

export class UpdateAaaDto extends OmitType(CreateAaaDto, ["name", "sex"]) {}

使用

  • 忽略掉 name,sex 字段,剩余字段必须传
ts
POST http://127.0.0.1:5000/aaa/45
Content-Type: application/json

{
    "age": 20,
    "hobbies": ["reading", "swimming"],
    "email": "xxxx@xxx.com"
}

IntersectionType

  • 合并两个 DTO

update-aaa.dto

ts
import { IntersectionType } from "@nestjs/mapped-types";
import { CreateAaaDto } from "./create-aaa.dto";
import { XxxDto } from "./xxxDto";
export class UpdateAaaDto extends IntersectionType(CreateAaaDto, XxxDto) {}

使用

ts

POST http://127.0.0.1:5000/aaa/45
Content-Type: application/json

{
    "name": "aaaaaaaa",
    "age": 20,
    "email": "xxxx@xxx.com",
    "sex":true,
    "xxx":"1234",
    "yyy":123,
    "hobbies": ["reading", "swimming"]
}

也可以合并使用

ts
import {
  IntersectionType,
  OmitType,
  PartialType,
  PickType,
} from "@nestjs/mapped-types";
import { CreateAaaDto } from "./create-aaa.dto";
import { XxxDto } from "./xxx.dto";

export class UpdateAaaDto extends IntersectionType(
  PickType(CreateAaaDto, ["name", "age"]),
  PartialType(OmitType(XxxDto, ["yyy"]))
) {}

从 CreateAaaDto 里拿出 name 和 age 属性,从 XxxDto 里去掉 yyy 属性变为可选,然后两者合并。

总结

注意

  1. PartialType 是把 dto 类型变为可选。

  2. PickType 是从已有 dto 类型中取某个字段。

  3. OmitType 是从已有 dto 类型中去掉某个字段。

  4. IntersectionType 是组合多个 dto 类型。