形如 page_size 的蛇形命名改成 pageSize 驼峰命名。
后端命名风格是蛇形,前端要求用小驼峰。所以在 axios 的拦截器对数据做处理,需要用到工具方法:把后端返回给前端的数据从蛇形处理成小驼峰,把前端提交到后端的数据从驼峰处理成蛇形。
方法封装:
import { isPlainObject, isArray, camelCase, snakeCase } from 'lodash-es'
/**
* 递归遍历
* @param value
* @param map 执行函数
* @returns
*/
function deepMapKeys(value: unknown, map: (key: string) => string): unknown {
if (isPlainObject(value)) {
const obj = value as Record<string, unknown>
const newObj: any = {}
for (const [key, val] of Object.entries(obj)) {
newObj[map(key)] = deepMapKeys(val, map)
}
return newObj
} else if (isArray(value)) {
const array = value
return array.map((val: unknown) => deepMapKeys(val, map))
} else {
return value
}
}
/**
* 转化为驼峰
* @param value
* @returns
*/
function toCamelCase(value: unknown): any {
return deepMapKeys(value, (key: string) => camelCase(key))
}
/**
* 转化为蛇形
* @param value
* @returns
*/
function toSnakeCase(value: unknown): any {
return deepMapKeys(value, (key: string) => snakeCase(key))
}
export { toCamelCase, toSnakeCase }
在axios的api拦截器中使用:(部分代码,只体现命名转换)
const config = {
// 默认地址请求地址,可在 .env 开头文件中修改
baseURL: import.meta.env.VITE_API_URL as string,
// 设置超时时间(10s)
timeout: ResultEnum.TIMEOUT as number,
// 跨域时候允许携带凭证
withCredentials: false
}
// 实例化axios
this.service = axios.create(config)
//客户端发送请求 -> [请求拦截器] -> 服务器
this.service.interceptors.request.use(
(config: AxiosRequestConfig) => {
config.data = toSnakeCase(config.data)
config.params = toSnakeCase(config.params)
return config
},
(error: AxiosError) => {
return Promise.reject(error)
}
)
//服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
this.service.interceptors.response.use(
(response: AxiosResponse) => {
const res: AxiosResponse = toCamelCase(response)
}