calc-oa-lib
Version:
calc oa library
337 lines (305 loc) • 12.2 kB
JavaScript
import Base from "./base";
import tool from "./tool";
import axios from "axios";
import qs from "qs";
//添加请求拦截器
axios.interceptors.request.use(
(config) => {
// let requestSource = config.requestSource;
// //兼容formdata情况
// let contentType = config?.headers["Content-Type"] ?? "";
// let data = config?.data ?? "";
// let isFormData = contentType.indexOf("form-data") >= 0;
// if (isFormData == false) {
// //1>校验动作权限,并添加公共字段
// if (requestSource != null && requestSource != undefined) {
// let dataObj = {};
// if (tool.isNullOrEmptyObject(data)) {
// dataObj = {};
// } else {
// dataObj = qs.parse(data);
// }
// let controlName = dataObj?._ControlName ?? "";
// // console.log(`controlName:${controlName}`);
// if (tool.isNullOrEmptyObject(controlName)) {
// requestSource.cancel(
// lanTool.lanContent("1002119_动作名不能为空!") ??
// "Control name can not be empty!"
// );
// return config;
// }
// // console.log(`controlName:${controlName}`);
// //若动作白名单不包含当前动作,则需要校验用户token是否为空
// if (!whiteList.actions.includes(controlName)) {
// //判断token是否为空
// let userToken = tool.getUserToken();
// // console.log(`userToken:${userToken}`);
// if (tool.isNullOrEmptyObject(userToken)) {
// requestSource.cancel(contantParam.errorCode_TokenInvalid);
// return config;
// }
// //判断用户账号是否为空
// let userName = tool.getUser()?.UserName ?? "";
// // console.log(`userName:${userName}`);
// if (tool.isNullOrEmptyObject(userName)) {
// requestSource.cancel(contantParam.errorCode_TokenInvalid);
// return config;
// }
// //添加公共字段
// dataObj = Object.assign({}, dataObj, {
// CurrentLanguageVersion: lanTool.getCurrentLV(),
// UserName: userName,
// _RegisterCode: userToken,
// });
// config.data = qs.stringify(dataObj);
// }
// }
// //2>处理loading
// if (!tool.isNullOrEmptyObject(data)) {
// let dataType = (typeof data).toLowerCase();
// if (dataType === "string") {
// data = qs.parse(data);
// }
// let isShowLoading = (data?._isShowLoading ?? "false").toLowerCase();
// // console.log(`_isShowLoading:${isShowLoading}`);
// if (isShowLoading == "true") {
// let instance = tool.showLoading();
// config.loadingInstance = instance;
// } else {
// tool.showNProgress();
// }
// }
// } else {
// //1>校验动作权限,并添加公共字段
// if (requestSource != null && requestSource != undefined) {
// let formData = {};
// if (data == null || data == undefined) {
// formData = new FormData();
// } else {
// formData = data;
// }
// if (
// !formData.has("_ControlName") ||
// tool.isNullOrEmptyObject(formData.get("_ControlName"))
// ) {
// requestSource.cancel(
// lanTool.lanContent("1002119_动作名不能为空!") ??
// "Control name can not be empty!"
// );
// return config;
// }
// let controlName = formData.get("_ControlName");
// // console.log(`controlName:${controlName}`);
// //若动作白名单不包含当前动作,则需要校验用户token是否为空
// if (!whiteList.actions.includes(controlName)) {
// //判断token是否为空
// let userToken = tool.getUserToken();
// // console.log(`userToken:${userToken}`);
// if (tool.isNullOrEmptyObject(userToken)) {
// requestSource.cancel(contantParam.errorCode_TokenInvalid);
// return config;
// }
// //判断用户账号是否为空
// let userName = tool.getUser()?.UserName ?? "";
// // console.log(`userName:${userName}`);
// if (tool.isNullOrEmptyObject(userName)) {
// requestSource.cancel(contantParam.errorCode_TokenInvalid);
// return config;
// }
// //添加公共字段
// formData.set("CurrentLanguageVersion", lanTool.getCurrentLV());
// formData.set("UserName", userName);
// formData.set("_RegisterCode", userToken);
// config.data = formData;
// }
// }
// //2>处理loading
// if (data != null && data != undefined) {
// let formData = {};
// if (data == null || data == undefined) {
// formData = new FormData();
// } else {
// formData = data;
// }
// let isShowLoading = (
// formData.get("_isShowLoading") ?? "false"
// ).toLowerCase();
// // console.log(`_isShowLoading:${isShowLoading}`);
// if (isShowLoading == "true") {
// let instance = tool.showLoading();
// config.loadingInstance = instance;
// } else {
// tool.showNProgress();
// }
// }
// }
// console.log(`axios.interceptors.request`);
return config;
},
(error) => {
return Promise.reject(error);
}
);
//添加响应拦截器
axios.interceptors.response.use(
async (response) => {
// //1>处理loading
// let loadingInstance = response?.config?.loadingInstance;
// if (loadingInstance != null && loadingInstance != undefined) {
// tool.hideLoading(loadingInstance);
// } else {
// tool.closeNProgress();
// }
const responseType = (response?.config?.responseType ?? "").toLowerCase();
//2>处理data
const status = response.status;
let statusText = response.statusText.toLowerCase();
if (status === 200 || statusText === "ok") {
if (responseType != "blob") {
response.data = tool.jObject(response.data);
// console.log(typeof response.data);
}
//若服务器返回错误ID=-10056,则表示登录失效,重定向到登录界面
// console.log(response.data);
// let { _MessageID } = response.data;
// _MessageID = _MessageID ?? "";
// if (_MessageID == -10056 && global.VM) {
// //关闭loading
// if (global.loadingInstance) {
// global.loadingInstance.close();
// }
// //退出登录
// await store.dispatch(contantParam.dispatch_UserLogout);
// //重定向到登录页
// let { fullPath, query } = global.VM.$route;
// if (tool.isNullOrEmptyObject(fullPath)) {
// return response;
// }
// global.VM.$router.replace({
// path: "/redirect" + fullPath,
// query,
// });
// return response;
// }
}
// console.log(`axios.interceptors.response`);
return response;
},
(error) => {
// if (global.loadingInstance) {
// global.loadingInstance.close();
// }
// tool.closeNProgress();
// let { message } = error;
// //若是令牌失效,则需要将页面重定向到登录页
// if (message == contantParam.errorCode_TokenInvalid && global.VM) {
// // console.log(global.VM);
// let { fullPath, query } = global.VM.$route;
// if (tool.isNullOrEmptyObject(fullPath)) {
// return Promise.reject(error);
// }
// global.VM.$router.replace({
// path: "/redirect" + fullPath,
// query,
// });
// return Promise.reject(error);
// }
// //判断是否主动cancel,若是,则提示错误
// let str = error.toString().toLowerCase();
// if (str.indexOf("cancel:") >= 0) {
// tool.showErrorMsg(message);
// }
return Promise.reject(error);
}
);
/**
* @description api工具类
*/
export default class apiTool extends Base {
//#region 属性
/**
* @type {object}
* @description 请求的相关参数
*/
static get apiParam() {
return {
loginAction_getLoginForm: "getLoginForm", //登录操作_获取登录表单对象
loginAction_login: "login", //登录操作_登录
loginAction_getDynamicPassword: "getDynamicPassword", //登录操作_获取动态密码
loginAction_forgetPassword: "forgetPassword", //登录操作_找回密码
};
}
//#endregion
//#region 构造函数
constructor() {
super();
}
//#endregion
/**
* 请求方法入口
* @param {object} opt
* @param {string} opt.url 用于请求的服务器 URL
* @param {string} opt.method 作为请求体发送的数据
* @param {function} opt.transformRequest 允许在向服务器发送前,修改请求数据,只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法,后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
* @param {function} opt.transformResponse 在传递给 then/catch 前,允许修改响应数据
* @param {object} opt.headers 将被发送的自定义请求头
* @param {object} opt.params 将与请求一起发送的 URL 参数,必须是一个无格式对象(plain object)或 URLSearchParams 对象
* @param {object} opt.data 为请求主体被发送的数据,只适用于这些请求方法 'PUT', 'POST', 和 'PATCH',在没有设置 `transformRequest` 时,必须是以下类型之一:,- string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams,- 浏览器专属:FormData, File, Blob,- Node 专属: Stream
* @param {number} opt.timeout 指定请求超时的毫秒数(0 表示无超时时间),如果请求超过 `timeout` 的时间,请求将被中断
* @param {boolean} opt.withCredentials 表示跨域请求时是否需要使用凭证
* @param {string} opt.responseType => 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
* @param {function} opt.onUploadProgress => 允许为上传处理进度事件
* @param {number} opt.maxContentLength => 定义允许的响应内容的最大尺寸
* @return {Promise}
* @author DylanXu 2020-12-14
* @example
*/
static request(opt) {
opt = opt || {};
// console.log("execute request...");
let defaultOpt = {
method: "post",
transformRequest: [
(data) => {
// 对data行任意转换处理
return data;
},
],
transformResponse: [
(data) => {
// 对data进行任意转换处理
return data;
},
],
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
params: {},
data: {},
timeout: "20000",
withCredentials: false,
responseType: "json",
onUploadProgress: (progressEvent) => {
//对原生进度事件的处理
},
maxContentLength: 0,
};
opt = Object.assign({}, defaultOpt, opt, {});
const { url = "" } = opt;
if (tool.isNullOrEmpty(url)) {
console.error(`url is null!`);
return false;
}
let source = axios.CancelToken.source();
opt.cancelToken = source.token; //设置中断请求用的cancelToken
opt.requestSource = source; //将source带入到请求配置
//兼容formdata情况
let contentType = opt.headers["Content-Type"] || "";
if (contentType == "application/x-www-form-urlencoded") {
//得到转换后的数据为 string 类型
opt.data = qs.stringify(opt.data);
}
//处理请求
return axios(opt);
}
}