我试图在我的项目中巧妙地使用 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: …Run Code Online (Sandbox Code Playgroud)