serialization - NestJS从snake_case到camelCase的序列化
问题描述
我想为 NestJS 控制器实现 JSON 请求/响应主体的自动序列化/反序列化,准确地说,自动将snake_case
请求主体 JSON 键转换为camelCase
在我的控制器处理程序处接收,反之亦然。
我发现使用class-transformer
's @Expose({ name: 'selling_price' })
,如下例所示(我使用的是 MikroORM):
// recipe.entity.ts
@Entity()
export class Recipe extends BaseEntity {
@Property()
name: string;
@Expose({ name: 'selling_price' })
@Property()
sellingPrice: number;
}
// recipe.controller.ts
@Controller('recipes')
export class RecipeController {
constructor(private readonly service: RecipeService) {}
@Post()
async createOne(@Body() data: Recipe): Promise<Recipe> {
console.log(data);
return this.service.createOne(data);
}
}
// example request body
{
"name": "Recipe 1",
"selling_price": 50000
}
// log on the RecipeController.createOne handler method
{ name: 'Recipe 1',
selling_price: 50000 }
// what I wanted on the log
{ name: 'Recipe 1',
sellingPrice: 50000 }
可以看到@Expose
注释完美地工作,但更进一步,我希望能够将其转换为实体上的属性名称:sellingPrice
,因此我可以将解析的请求正文直接传递给我的服务和我的存储库方法this.recipeRepository.create(data)
。当前条件是该sellingPrice
字段将为空,因为存在该selling_price
字段。如果我不使用@Expose
,则需要写入请求 JSON camelCase
,这不是我喜欢的。
我可以执行 DTO 和构造函数以及分配字段,但我认为这是相当重复的,并且由于我的命名偏好,我将有很多字段要转换:snake_case
在 JSON 和数据库列以及camelCase
所有 JS/TS 部分上。
有没有办法可以干净利落地做这个把戏?也许已经有解决方案了。snake_case
也许是一个可以全部转换为的全局拦截器,camel_case
但我也不确定如何实现一个。
谢谢!
解决方案
您可以使用mapResult()
ORM 中的方法,该方法负责将原始数据库结果(对您而言是 snake_case)映射到实体属性名称(对您而言是 camelCase):
const meta = em.getMetadata().get('Recipe');
const data = {
name: 'Recipe 1',
selling_price: 50000,
};
const res = em.getDriver().mapResult(data, meta);
console.log(res); // dumps `{ name: 'Recipe 1', sellingPrice: 50000 }`
此方法基于实体元数据进行操作,将键从fieldName
(默认为基于所选命名策略的值)更改。
推荐阅读
- javascript - JavaScript 24 时间自动计算 Adobe Form Field 的工时?
- proof - 证明自然 (n) 为零
- ios - 如何从视图控制器中删除导航栏
- python - 如何打印仅包含字符串中字母的单词?
- machine-learning - 在线广告和机器学习
- angular - 为什么我无法获取项目总数并将其绑定到 ngModel?
- asp.net-core - IdentityServer4 从 appsettings.json 读取客户端声明
- axapta - 有什么简单的方法可以检查已发布服务的使用情况吗?
- ios - 在设置包中的设置更改时收到通知(在 Xamarin iOS 中)
- android - 如何使用 kotlin android 扩展从 radiogroup 中检索单选按钮