我的照片和标签对象有 DTO,如下所示:
export class PhotoDto {
readonly title: string
readonly file: string
readonly tags: TagDto[]
}
export class TagDto {
readonly name: string
}
我用PhotoDto
in my photo.service.ts
并最终在photo.controller.ts
用于创建照片:
// In photo.service.ts
async create(createPhotoDto: PhotoDto): Promise<PhotoEntity> {
// ...
return await this.photoRepo.create(createPhotoDto)
}
// In photo.controller.ts
@Post()
async create(@Body() createPhotoDto: PhotoDto): Promise<PhotoEntity> {
// ...
}
但是,API 主体中的输入预计具有以下结构:
{
"title": "Photo Title",
"file": "/some/path/file.jpg",
"tags": [
{
"name": "holiday"
},
{
"name": "memories"
}
]
}
如何更改输入形状Body
接受这个结构?
{
"title": "Photo Title",
"file": "/some/path/file.jpg",
"tags": ["holiday", "memories"]
}
我尝试过创建 2 个不同的 DTO,一个CreatePhotoDto
and an InputPhotoDto
,一个用于控制器中所需的输入形状,一个用于服务和实体,但这最终会变得非常混乱,因为在 2 个 DTO 之间进行转换需要大量工作。
获得与输入形状不同的正确方法是什么Body
of a Post
请求然后是否已转化为实体所需使用的DTO?