node Koa2 中后台返回字段由下划线改为驼峰的中间件

// toHump.js
const toHump = async (ctx, next) => {
    ctx.write = (obj) => ctx.body = toHumpFun(obj)
    await next()
}

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
            }

            if (typeof element === 'object' && element !== null) {
                result[newKey] = toHumpFun(element)
            }
        }
    }
    return result
}

module.exports = toHump
// app.js
const toHump = require('./toHump')
app.use(toHump) // 需要放在引用路由之前

使用 ctx.write(data) 替换 ctx.body = data

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。