 Egg接口返回字段名下划线转驼峰
          Egg接口返回字段名下划线转驼峰
        
  # 中间件 - 接口返回字段名下划线转驼峰
参考资料:
# 编写中间件
点击查看 /app/middleware/toHump.js 代码
'use strict'
/**
 * 接口返回数据字段下划线转小驼峰
 * 用法:使用 ctx.write(results) 代替 ctx.body = results
 */
function toHumpFun(obj) {
  const result = Array.isArray(obj) ? [] : {}
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const element = obj[key]
      const index = key.indexOf('_')
      let newKey = key
      if (index === -1 || key.length === 1) {
        result[key] = element
      } else {
        const keyArr = key.split('_')
        const newKeyArr = keyArr.map((item, index) => {
          if (index === 0) return item
          return item.charAt(0).toLocaleUpperCase() + item.slice(1)
        })
        newKey = newKeyArr.join('')
        result[newKey] = element
      }
      // element instanceof Date 判断日期格式不做转换,否则日期格式会变成 "{}"
      if (typeof element === 'object' && element !== null && !(element instanceof Date)) {
        result[newKey] = toHumpFun(element)
      }
    }
  }
  return result
}
module.exports = () => {
  return async (ctx, next) => {
    ctx.write = (obj) => {
      ctx.body = toHumpFun(obj)
    }
    await next()
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 使用中间件
中间件编写完成后,我们还需要手动挂载,在 /config/config.default.js 中加入配置
module.exports = {
  // 配置需要的中间件,数组顺序即为中间件的加载顺序
  middleware: [ 'toHump' ],
};
1
2
3
4
2
3
4
# 在业务中使用
使用 ctx.write(results) 代替 ctx.body = results
上次更新: 2021-05-10 17:15:54