{
user_name: 'xxx',
email_address: 'xxx'
}
{
userName: 'xxx',
emailAddress: 'xxx'
}
const reduce = require('lodash/reduce')
function createTransform (transformKey) {
function transformObject (value, depth = -1) {
if (depth === 0 || value == null || typeof value !== 'object') {
return value
}
if (Array.isArray(value)) {
return value.map(item => transformObject(item, depth - 1))
}
return _reduce(value, (prev, val, key) => {
// 将 key 进行转换
prev[transformKey(key)] = transformObject(val, depth - 1)
return prev
}, {})
}
return transformObject
}
const camelCase = require('lodash/camelCase')
const deepCamcel = createTransform(camelCase)
deepCamcel({
a_b: {
c_d: {
e_f: 'g_h'
}
}
}))
// 结果
{
aB: {
cD: {
eF: 'g_h' // 注意,只会转换 key,不会转换内容
}
}
}
deepCamcel({
a_b: {
c_d: {
e_f: 'g_h'
}
}
}, 1))
// 结果如下,即只转换对象的第一层 key
{
aB: {
c_d: {
e_f: 'g_h'
}
}
}
const snakeCase = require('lodash/snakeCase')
const deepSnake = createTransform(snakeCase)
deepSnake({
aB: {
cD: {
eF: 'gH'
}
}
})
// 结果
{
a_b: {
c_d: {
e_f: 'gH'
}
}
}
const snakeCase = require('lodash/snakeCase')
const deepSnake = createTransform(snakeCase)
// 使用拦截器
request.interceptors.request.use(transformKeysToSnakeCase);
function transformKeysToSnakeCase(config) {
// POST
if (config.data) {
config.data = deepSnake(config.data);
}
// GET
if (config.params) {
config.params = deepSnake(config.params);
}
return config;
}
const camelCase = require('lodash/camelCase')
const deepCamcel = createTransform(camelCase)
// 使用拦截器
request.interceptors.response.use(transformKeysToCamelCase);
function transformKeysToCamelCase(response) {
if (response.data) {
let caseOptions = null;
if (response.config) {
caseOptions = response.config.responseCaseOptions;
}
response.data = deepCamcel(response.data);
}
return response;
}