【问题标题】:How to build a DTO based on multiple DTOs?如何基于多个 DTO 构建 DTO?
【发布时间】:2021-01-21 06:37:51
【问题描述】:

我有几个 DTO 供用户使用

第一:

export class UserProfileContactDto {
  @ApiProperty()
  @IsNotEmpty()
  @IsEmail()
  readonly email: string;

  @ApiProperty()
  @IsNotEmpty()
  @IsPhoneNumber('ua')
  readonly phone: string;
}

第二:

export class UserProfileDataDto {
  @ApiProperty()
  @IsNotEmpty()
  @IsString()
  readonly name: string;

  @ApiProperty({ required: false })
  @IsString()
  readonly lastname: string;

  @ApiProperty()
  @IsNotEmpty()
  @IsEnum(userGenderEnum)
  readonly gender: userGenderEnum;
}

我想基于这些 DTO 获得第三个 DTO:

export class UserCreateDto extends UserProfileDataDto, UserProfileContactDto{  

  @ApiProperty()
  @IsNotEmpty()
  @IsString()
  @Matches(/((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/, {
    message: 'password too weak',
  })
  readonly password: string;
}

但是我不能对多个类使用扩展,并且接口对我不起作用,因为我正在使用类验证器库。
你怎么能解决我的问题?

【问题讨论】:

    标签: angularjs typescript nestjs dto


    【解决方案1】:

    由于 TS 不支持多重继承并且您不能使用接口,您可以使用联系人数据的组合来解决此问题(但它需要您更改接口):

    export class UserProfileDataDto {
      @ApiProperty()
      @IsNotEmpty()
      @IsString()
      readonly name: string;
    
      @ApiProperty({ required: false })
      @IsString()
      readonly lastname: string;
    
      @ApiProperty()
      @IsNotEmpty()
      @IsEnum(userGenderEnum)
      readonly gender: userGenderEnum;
    
      @ApiProperty()
      @IsNotEmpty()
      readonly contactData: UserProfileContactDto;
    }
    

    然后您可以像对 UserCreateDto 所做的那样从此类扩展。

    【讨论】:

    • 感谢您的回复。我的主类 - UserCreateDto 实际上不应该扩展两个类,而是五个或更多 - UserProfileDataDto、UserProfileContactDto、UserAddressDto、UserOrder、UserLogin。可以在 UserCreateDto 中描述所有这些,但我需要单独使用一些字段组。
    • 即更新地址,需要UserAddressDto。我可以使用 Partial 但会有太多不必要的非地址字段。也许还有另一种组织方式?
    • 在这种情况下我仍然会使用合成。例如。对于地址,将UserAddressDto 类型的新属性address 添加到UserCreateDto
    • 谢谢!我误解了你的意思。现在我明白你的意思了。我希望事情是这样的。如果没有,我会写下我的困难
    猜你喜欢
    • 2020-12-12
    • 2023-04-02
    • 2019-04-27
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2016-03-20
    • 1970-01-01
    相关资源
    最近更新 更多