项目哪些需求——请求数据格式的转换

1,747 阅读2分钟

前言

随着项目的进度紧张,很多时候都是以结果为导向的。所以这次自己在开发中偶然遇到了一个需求,就是原来所有的接口请求,返回数据都是以下划线命令规则的,原后台也是做了这层数据的转换,将自己驼峰命名统一转换为下划线。但由于牵涉到和其他项目的对接,由于命名不统一,数据有一些是下划线,有一些是驼峰,所以背锅的前端,接到一个需求,要将原来的下划线全部改成驼峰命名规则。

需求分析

  1. 时间问题,如果针对下滑线去改成驼峰,那么前端牵涉到所有字段都需要改动,而且可能改错了,也是需要来回折腾
  2. 工作量大,现场也只有我这一个独苗,感觉会被折腾死。
  3. .......

技术分析

  1. 由于项目使用了axios做数据请求,那么必将提供了,axios.interceptors.request.interceptors.response的回调钩子的。
  2. 那么所有的请求数据,和返回数据都可以是在请求前,和响应后可以拿到的。

具体实现代码

utils/tools.js

function underline2Hump(s) {
  return s.replace(/_(\w)/g, function(all, letter) {
    return letter.toUpperCase()
  })
}

// 字符串的驼峰格式转下划线格式,eg:helloWorld => hello_world
function hump2Underline(s) {
  return s.replace(/([A-Z])/g, '_$1').toLowerCase()
}

// JSON对象的key值转换为驼峰式
function jsonToHump(obj) {
  if (obj instanceof Array) {
    obj.forEach(function(v, i) {
      jsonToHump(v)
    })
  } else if (obj instanceof Object) {
    Object.keys(obj).forEach(function(key) {
      var newKey = underline2Hump(key)
      if (newKey !== key) {
        obj[newKey] = obj[key]
        delete obj[key]
      }
      jsonToHump(obj[newKey])
    })
  }
}

// JSON对象的key值转换为下划线格式
function jsonToUnderline(obj) {
  if (obj instanceof Array) {
    obj.forEach(function(v, i) {
      jsonToUnderline(v)
    })
  } else if (obj instanceof Object) {
    Object.keys(obj).forEach(function(key) {
      var newKey = hump2Underline(key)
      if (newKey !== key) {
        obj[newKey] = obj[key]
        delete obj[key]
      }
      jsonToUnderline(obj[newKey])
    })
  }
}
export default {
   // JSON对象的key值转换为驼峰式
  jsonToHumpNew: function (obj) {
    jsonToHump(obj)
  },
  // JSON对象的key值转换为下划线格式
  jsonToUnderlineNew: function (obj) {
    jsonToUnderline(obj)
  }
}

utils/request.js

import tools from './tools'
<!--将请求数据,下滑线的提交数据改成驼峰 -->
axios.interceptors.request.use(function (request) {
   // 针对get,data,put,特性,做数据拦截处理
   if(request.params) {
      temdata = JSON.parse(JSON.stringify(request.params))
      tools.jsonToHumpNew(temdata)
      request.params = temdata
    }
    if(request.data) {
      temdata = JSON.parse(JSON.stringify(request.data)) // 做下深拷贝,防止应用类型,改变原来的值
      tools.jsonToHumpNew(temdata)
      request.data = temdata
    } 
  return request
})
<!--将接口响应数据,驼峰数据改成下划线 -->
axios.interceptors.response.use(function (request) {
   tools.jsonToUnderlineNew(data.data)
   return data.data
})
  

附上性能测试

总结

哈哈,over,简单粗暴。