大家好,
我正在研究 NestJs,当使用 DTO 和 JSON 进行序列化时,我遇到了一个不常见的情况。
我的 Json 带有以下参数:
{
"category": 1
}
但是我需要使用这个属性作为“类型”,所以在我的DTO中是:
export class CreateClassDto {
@IsNumber()
type: CustomType;
}
如何将 Json 中的“类别”参数解析为 DTO 上的参数“类型”?
当我更改 DTO 中的参数名称时,我的实体无法解析,服务崩溃,并且我无法保存我的数据库。
在 Swift 语言中我可以使用类似的东西:
struct Entity: Codable {
let type: CustomType
enum CodingKeys: String, CodingKey {
case type = "category"
}
}
是否有类似的东西或装饰器说我收到的参数需要是我的内部参数?
我尝试使用@Expose(),但我需要将“类别”转换为我的数据库和应用程序的“类型”。
我读过这篇文章: NestJS 更改发布请求中收到的参数名称
但是不太明白。
有人有这样做的例子吗?
关注
我认为 javascript/typescript 目前还没有 swift 那样的能力。但这是我针对您的情况提出的解决方法。我一直在我的所有项目中使用这种技术,以保持事物整洁和独立。
D到
export class CreateClassDto {
@IsNumber()
category: CustomType;
static toJSON(data: CreateClassDto) {
return {
type: data.category,
};
}
}
在控制器中
async createClass(@Body() body: CreateClassDto) {
const data = CreateClassDto.toJSON(body);
// now you can pass the data to the respective service
await this.classService.save(data)
}
希望这有帮助。