/* eslint-disable */
import axios from 'axios';
import qs from 'qs';
import merge from 'lodash/merge';
import router from '@/router';
import { ElMessage } from 'element-plus';
//计时器,安全策略,如果超过指定时间没有任何请求动作,默认退出登录
let secureTimer = null;
const SECURE_TIME = 1000 * 60 * 60 * 2; //默认2小时
let api = '/api';
if (process.env.NODE_ENV === 'production' && window.env) {
api = window.env.REQUEST_LOC;
}
export class Eventer{
constructor(){
this.registries = [];
}
register(key, cb){
this.registries.push({key, cb})
}
emit(context){
this.registries.forEach((item)=>{
//判断whiteList的key,有的话再执行
context.whiteList.forEach((group)=>{
if(item.key.indexOf(group) > -1){ //如果分组中有该组名,比如 /config/basic-param
item.cb.call(context)
}
})
})
return context;
}
}
export const ajaxEventer = new Eventer();
ajaxEventer.register('/config/basic-param', function () {
merge(this.config, {
// timeout: 120000, // 2分钟
timeout: 6E5, // 10分钟
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
});
});
// 设置 baseUrl
ajaxEventer.register('/config/url-prefix', function () {
if (this.config.noPrefix) { // 允许不加api或者任何前缀
this.config.url = `${this.config.url}`;
} else {
this.config.url = `${api}/${this.config.url}`;
}
if(location.href.includes('url=1')){
console.log(this.config.url);
}
this.config.url = this.config.url.replace(/\/+/g, '/');
});
// get 请求处理 url, pathParams, pathQuery决定使用情况
ajaxEventer.register('/config/path-params', function () {
// this.config.url = kr.url.inject(this.config.url, this.config.pathParams, this.config.pathQuery);
});
// post 数据处理
ajaxEventer.register('/config/form-data', function () {
if (this.config.data) {
// this.config.data = qs.stringify(this.config.data);
}
if (this.config.formData) {
this.config.data = qs.stringify(this.config.formData);
}
});
// result 中间件
ajaxEventer.register('/result/analysis', function () {
const { result } = this;
if (!(result instanceof Error)) {
if (result.status === 200 || result.status === 201) {
if(result.data instanceof Blob){
return
}
const {
code, warnMessage, data, success, message, msg
} = result.data;
switch (code) {
case 0:
if (warnMessage) { // 新建编辑数据,异常,不堵塞。
this.result = {
message: warnMessage,
result: data,
};
} else {
this.result = {
code,
message,
success,
result: data
};
}
break;
case undefined:// 极验返回数据不同
this.result = result;
break;
default:
this.result = Error(code);
this.errorInfo = {
code,
message: msg || message,
};
}
} else {
this.result = Error();
}
} else {
this.result = Error();
let data = result.response && result.response.data;
// 补丁,配置网关后, 当登录不成功时跳转到登录页面
// 网关暂时无法抛出success类型的异常
data = data || {};
if (data.code === 100000005 || data.code === 100000006) {
this.errorInfo = data;
} else if (data.code === 100000002) {
this.errorInfo = {
message: data.message || '授权证书已过期'
};
setTimeout(() =>{
let tenantId = __g_store__.getters['user/getTenantId'];
let currentRouter = window.location.hash.split('/')[1];
__g_router__.replace({ path: '/login', query: { auth: false, tenantId }});
currentRouter.name === 'login' && window.location.reload();
}, 200);
} else if (data.code === 101005) {
this.errorInfo = {
message: '授权信息已变更,请重新登录!'
};
setTimeout(() =>{
let currentRouter = window.location.hash.split('/')[1];
currentRouter === 'login' ? window.location.reload() : __g_router__.replace({ path: '/login'});
}, 200);
}else {
this.errorInfo = {
message: data.message || result || '请求超时',
};
}
}
});
ajaxEventer.register('/result/handle-error', function () {
const { result, errorInfo } = this;
if (result instanceof Error) {
if (errorInfo) {
if ([100000001, 100000005, 100000006].includes(errorInfo.code)) {
__g_store__.dispatch('login/clearUserState');
// 免登录页面不需要跳转登录页
const { fullPath, path } = __g_router__.currentRoute;
if (!__g_config__.loginWhiteList.includes(path)){
__g_router__.replace({
path: '/login',
query: {
redirect: fullPath,
},
});
}
} else if(101005 == errorInfo.code){
__g_router__.replace({
path: '/login',
query: {
redirect: fullPath,
},
});
} else {
// kr.ui.error(errorInfo.message || '服务暂不可用,请稍后重试');
ElMessage.error(errorInfo.message);
}
}
}
});
// post - data:{}, get - params: {}
export default async function ajax(config, whiteList = [], blackList = [], needCon = false) {
if(secureTimer){
clearTimeout(secureTimer);
}
secureTimer = setTimeout(()=>{
console.log('getout');
document.cookie = `zrAccessToken=;expires=${new Date(0).getTime()}`;
document.cookie = `accessToken=;expires=${new Date(0).getTime()}`;
clearTimeout(secureTimer);
window.location.href = '/#/login';
}, SECURE_TIME);
debugger
// eslint-disbaled-next-line
let context = ajaxEventer.emit({
whiteList: ['/config'].concat(whiteList),
blackList, //黑名单暂时不生效,不使用
config,
});
let result = null;
try {
result = await axios.request(context.config);
} catch (e) {
result = e;
}
context = ajaxEventer.emit({
whiteList: ['/result'].concat(whiteList),
blackList, //黑名单暂时不生效,不使用
result,
config,
});
if (needCon) {
return context;
}
if (context.result instanceof Error) {
throw context.result;
}
return context.result;
}
请求方法例如:
// 更新资料室
export const batchUpdateOrRenameFile = async (extra = {}) => {
const result = await ajax({
method: 'post',
url: '/file/batchUpdateOrRenameFile',
...extra,
});
return result;
};