【发布时间】:2020-07-23 04:57:39
【问题描述】:
我试图在我的项目中巧妙地使用 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"
}
}
我的控制器负责使用自定义 ValidationPipe 检查字段:
@Post()
@UsePipes(new ValidationPipe())
create(@Body() data: CableDto) {
return this.cablesService.create(data);
}
我在很多地方读到,在最佳实践中,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;
}
这是我用于电缆交互的 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;
}
}
我知道这三种双向转换 DTO 和实体的方法感觉很脏,这就是我在这里的原因..
我的服务对于一个简单的创建或获取请求知道:
async create(dto: CableDto): Promise<CableDto> {
const cable = await this.cablesRepository.save(CableDto.toEntity(dto));
return await this.findById(cable.CAB_Id)
}
我相信有更简单的解决方案可以实现这一目标,或者至少是一种正确的方法。
有什么想法吗?
谢谢。
【问题讨论】:
标签: typescript nestjs dto typeorm