NestJs - DTO 和实体

Yan*_*ver 8 dto typescript typeorm nestjs

我试图在我的项目中巧妙地使用 DTO 和实体,但它似乎比它应该的更复杂。我正在构建一个用于管理库存的后端,我使用 NestJs 和 TypeOrm。

我的客户正在向我发送一组数据并抛出一个 POST 请求,比方说:

{
  "length": 25,
  "quantity": 100,
  "connector_A": {
    "id": "9244e41c-9da7-45b4-a1e4-4498bb9de6de"
  },
  "connector_B": {
    "id": "48426cf0-de41-499b-9c02-94c224392448"
  },
  "category": {
    "id": "f961d67f-aea0-48a3-b298-b2f78be18f1f"
  }
}
Run Code Online (Sandbox Code Playgroud)

我的控制器有责任使用自定义 ValidationPipe 来检查该字段:

@Post()
  @UsePipes(new ValidationPipe())
  create(@Body() data: CableDto) {
    return this.cablesService.create(data);
}
Run Code Online (Sandbox Code Playgroud)

我在很多地方都读到过,在最佳实践中,RAW 数据应该转换为 DTO,而在插入数据时,我应该将我的 DTO 转换为 typeOrm 实体。

我对这个方法没问题,但我发现它非常复杂,当我的表和前缀名词之间存在关系时,它会更复杂。

这是我的实体电缆

@Entity('t_cable')
export class Cable {

  @PrimaryGeneratedColumn('uuid')
  CAB_Id: string;

  @Column({
    type: "double"
  })
  CAB_Length: number;

  @Column({
    type: "int"
  })
  CAB_Quantity: number;

  @Column()
  CON_Id_A: string

  @Column()
  CON_Id_B: string

  @Column()
  CAT_Id: string

  @ManyToOne(type => Connector, connector => connector.CON_Id_A)
  @JoinColumn({ name: "CON_Id_A" })
  CON_A: Connector;

  @ManyToOne(type => Connector, connector => connector.CON_Id_B)
  @JoinColumn({ name: "CON_Id_B" })
  CON_B: Connector;

  @ManyToOne(type => Category, category => category.CAB_CAT_Id)
  @JoinColumn({ name: "CAT_Id" })
  CAT: Category;

}
Run Code Online (Sandbox Code Playgroud)

这是我用于电缆交互的 DTO:

export class CableDto {

  id: string;

  @IsOptional()
  @IsPositive()
  @Max(1000)
  length: number;
  quantity: number;

  connector_A: ConnectorDto;
  connector_B: ConnectorDto;
  category: CategoryDto

  public static from(dto: Partial<CableDto>) {
    const it = new CableDto();
    it.id = dto.id;
    it.length = dto.length;
    it.quantity = dto.quantity;
    it.connector_A = dto.connector_A
    it.connector_B = dto.connector_B
    it.category = dto.category
    return it;
  }

  public static fromEntity(entity: Cable) {
    return this.from({
      id: entity.CAB_Id,
      length: entity.CAB_Length,
      quantity: entity.CAB_Quantity,
      connector_A: ConnectorDto.fromEntity(entity.CON_A),
      connector_B: ConnectorDto.fromEntity(entity.CON_B),
       category: CategoryDto.fromEntity(entity.CAT)
    });
  }

  public static toEntity(dto: Partial<CableDto>) {
    const it = new Cable();
    if (dto.hasOwnProperty('length')) {
      it.CAB_Length = dto.length;
    }
    if (dto.hasOwnProperty('quantity')) {
      it.CAB_Quantity = dto.quantity;
    }
    if (dto.hasOwnProperty('connector_A')) {
      it.CON_Id_A = dto.connector_A.id;
    }
    if (dto.hasOwnProperty('connector_B')) {
      it.CON_Id_B = dto.connector_B.id;
    }
    if (dto.hasOwnProperty('category')) {
      it.CAT_Id = dto.category.id;
    }
    return it;
  }
}
Run Code Online (Sandbox Code Playgroud)

我知道这三种双向转换 DTO 和实体的方法感觉很脏,这就是我在这里的原因..

我的简单创建或获取请求服务知道:

async create(dto: CableDto): Promise<CableDto> {
  const cable = await this.cablesRepository.save(CableDto.toEntity(dto));
  return await this.findById(cable.CAB_Id)
}
Run Code Online (Sandbox Code Playgroud)

我相信有更简单的解决方案可以实现这一目标,或者至少有一种正确的方法来做到这一点。

任何的想法 ?

谢谢你。

Fab*_*osa 2

对于所有类型转换(例如 DTO > 实体或实体 > DTO),我开发了一个库metamorphosis-nestjs来简化对象的转换。
它为 NestJS 添加了缺少的可注入转换服务概念,用于转换器提供的所有转换,提前注册到转换服务中(如 Java 应用程序中 Spring 框架提供的转换服务)。

所以在你的情况下,使用 typerORM:

  1. npm install --save @fabio.formosa/metamorphosis-nest
    
    Run Code Online (Sandbox Code Playgroud)
  2. import { MetamorphosisNestModule } from '@fabio.formosa/metamorphosis-nest';
    
    @Module({
      imports: [MetamorphosisModule.register()],
      ...
    }
    export class MyApp{ }
    
    Run Code Online (Sandbox Code Playgroud)
  3. import { Convert, Converter } from '@fabio.formosa/metamorphosis';
    
    @Injectable()
    @Convert(CableDto, Cable)
    export default class CableDtoToCableConverter implements Converter<CableDto, Promise<Cable>> {
    
    constructor(private readonly connection: Connection){}
    
    public async convert(source: CableDto): Promise<Cable> {
      const cableRepository: Repository<Cable> = this.connection.getRepository(Cable);
      const target: Product | undefined = await cableRepository.findOne(source.id);
      if(!target)
        throw new Error(`not found any cable by id ${source.id}`);
      target.CAB_Length = source.length;
      target.CAB_Quantity = source.quantity;
      ... and so on ...
      return target;
    }
    
    Run Code Online (Sandbox Code Playgroud)

}

最后你可以注入并使用 conversionService 任何你想要的:

 const cable = <Cable> await this.convertionService.convert(cableDto, Cable);
Run Code Online (Sandbox Code Playgroud)

从 Cable 到 CableDto 的转换器更简单。

获取自述文件以了解metamorphosis-nestjs的示例和所有优点。