# 中间件 - 接口返回字段名下划线转驼峰 {#中间件-接口返回字段名下划线转驼峰}
参考资料:
# 编写中间件 {#编写中间件}
点击查看 /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() } }
# 使用中间件 {#使用中间件}
中间件编写完成后,我们还需要手动挂载,在 /config/config.default.js
中加入配置
module.exports = {
// 配置需要的中间件,数组顺序即为中间件的加载顺序
middleware: [ 'toHump' ],
};
# 在业务中使用 {#在业务中使用}
使用 ctx.write(results)
代替 ctx.body = results