Map request object parameters keys to custom keys before request object hits controller

时间:2019-01-09 22:03:02

标签: node.js typescript express loopbackjs

I've got a Loopback 4 application and the request object's property keys are snake_case and they map to our DB column names which are StudlyCase. Let's say I want the application property names to be camelCase. So the data's keys will go through the following lifecycle:

Request Parameter (snake_case)
        ||
        \/
Model Property (camelCase)
        ||
        \/
MySQL Column (StudlyCase)

Loopback 4 takes care of the mapping between Model Property and MySQL Column. It has decorators that allow me to specify the DB column name associated to a Model Property while using the same property keys as the request object, like:

@property({
  mysql: {
    columnName: 'FirstName',
  },
  type: 'string',
  required: true,
})
first_name: string;

I'm looking for an Express package or another simple way to apply custom mapping of the keys in request objects before they reach the controller, rather than at the data model layer, as Loopback's decorators allow.

Laravel has exactly what I'm looking for. They call it the Eloquent API Resource layer. It's just an array of mappings, like:

[
  'first_name' => 'firstName',
  'last_name' => 'lastName',
  ... more mappings ...
]

But the point is that this mapping occurs before even the controller receives the request object.

How can this be accomplished in Loopback 4 / Express / NodeJS?

UPDATE: It looks like Loopback 4 wraps Express in its @loopback/rest package's Sequence APIs. I'll post another update once I've got this fully figured out, as well as the answer.

Something I forgot to mention is that the Response object's property keys also needs to be the same case as the Request object's property keys (snake_case in my case). I'll post a TypeScript/LB4 solution.

1 个答案:

答案 0 :(得分:0)

如果您正在寻找将参数转换为驼峰的方法,请尝试ccqp表达中间件。