写在前面: 在低代码平台开发过程中,我们定义了相应接口规范,但是有时候由于云端同学代码本身限制,无法实现我们的前端接口规范,于是需要实现对接口数据结构进行前置和后置处理
实现思路
在低代码平台开发环境中,我们基于json实现页面结构配置,于是具体的前置后置处理逻辑必须是动态的,因此不会写死在 axios 的拦截器中,因此我们需要对 axios.get 实现装饰
直接上代码
const emptyFn = () => {}
export const requestMethod = (item) => {
const useRequest = request[item.methodType];
const before = item.requestAdaptor ? new Function('paramsObj', item.requestAdaptor) : emptyFn;
const after = item.responseAdaptor ? new Function('res', item.responseAdaptor) : emptyFn;
Function.prototype.before = function (fn) {
let _that = this;
return function (url, params) {
let temParams = fn.call(this, params);
return _that.call(this, url, temParams)
}
}
Function.prototype.after = function (fn) {
let _that = this;
return async function () {
let temp = await _that.apply(this, arguments);
let result = fn.call(this, temp);
return result
}
}
return useRequest.before(before).after(after)
}
以上代码实现了对 useRequest 的修饰,实现了请求前置方法对请求参数修饰,后置方法对返回结果的修饰,验证完毕后完美符合预期。
在json中通过配置前置和后置方法逻辑,很好实现了需求。