import { message, Modal } from "ant-design-vue";
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import axiosRetry from "axios-retry";
import { contentType, dataName, messageName, requestTimeout, statusName, successName } from "@/config/network";
import { noShowApiMessage, noShowApiMessageSuccess } from "@/config/custom";
import i18n from "@/locales/i18n";
import router from "@/router/index";
import store from "@/store";
import { AjaxRes } from "@/types/common";
import { createSign, getSessionId } from "@/utils/clientStorage";
import { isContainChinese } from "@/utils/network";
axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
axios.defaults.timeout = requestTimeout;
axios.defaults.headers["Content-Type"] = contentType;
axios.interceptors.request.use(
(config: AxiosRequestConfig) => {
const token = store && store.state["user"].token;
const language = store && store.state["app"].language;
const website = store && store.state["app"].website;
const currency = store && store.state["app"].currency;
const SessionId = getSessionId() as string;
config.headers = {
Language: currency === "EUR" ? "eu" : language,
Website: website,
Currency: currency,
token: token,
};
if (SessionId) config.headers["SessionId"] = SessionId;
if (token) {
config.headers["Authorization"] = `Bearer ${token}`;
}
if (config.data && Object.keys(config.data).length > 0) {
Object.keys(config.data).forEach((item: string) => {
if (typeof config.data[item] === "string") config.data[item] = config.data[item].trim();
});
}
if (config.params && Object.keys(config.params).length > 0) {
Object.keys(config.params).forEach((item: string) => {
if (typeof config.params[item] === "string") config.params[item] = config.params[item].trim();
});
}
return { ...config, url: createSign(config.url as string) };
},
(error: AxiosError) => {
return Promise.reject(error);
}
);
axios.interceptors.response.use(
(response: AxiosResponse) => {
if (response.headers._token && response.config.url !== "/api/base/v1/simplelogin") {
store.commit("user/setTokenInfo", response.headers._token);
}
switch (response.data[statusName]) {
case 401:
break;
case 403:
break;
case 404:
message.error(response.data[messageName]);
break;
case 500:
(!location.pathname.includes("/auth/") || !noShowApiMessage.some((t) => (response.config.url as string).includes(t))) &&
isContainChinese(response.data[messageName]) &&
Modal.error({
title: i18n.t("接口温馨提醒"),
content: i18n.t(response.data[messageName] ? String(response.data[messageName]) : "接口发生异常"),
centered: true,
okText: i18n.t("确定") as string,
});
break;
default:
if (response.data[messageName] && response.data[successName] && !response.data[dataName]) {
if (!noShowApiMessageSuccess.some((t) => (response.config.url as string).includes(t))) {
message.success(i18n.t(String(response.data[messageName]) || "操作成功") || i18n.t("操作成功"));
}
}
if (response.data[messageName] && !response.data[successName] && !response.data[dataName] && isContainChinese(response.data[messageName])) {
Modal.error({
title: i18n.t("接口温馨提醒"),
content: i18n.t(response.data[messageName] ? String(response.data[messageName]) : "接口发生异常") || i18n.t("接口发生异常"),
centered: true,
okText: i18n.t("确定") as string,
});
}
break;
}
return response;
},
(error: AxiosError) => {
if (error.response && error.response.status === 403) {
message.warning(error.response.statusText);
}
if (error.response && error.response.status === 404) {
message.warning(error.response.statusText);
}
if (error.response && error.response.status === 405) {
message.warning(error.response.statusText);
}
if (error.response && error.response.status === 415) {
message.warning(error.response.statusText);
}
if (error.response && error.response.status === 501) {
router.push("/exception/501").then(() => {});
}
if (error.response && [504, 502, 500, 400].includes(error.response.status)) {
router.push("/exception/500").then(() => {});
}
return Promise.reject(error);
}
);
axiosRetry(axios, {
retries: 3,
retryDelay: (retryCount: number) => {
return retryCount * 1500;
},
shouldResetTimeout: true,
retryCondition: (error: AxiosError) => {
return error.message.includes("timeout") || error.message.includes("Network Error");
},
});
export const ajax = ({ url, method = "GET", params = {}, data = {}, baseURL = undefined, headers = {}, responseType = "json" }: AxiosRequestConfig): Promise<AjaxRes> => {
return new Promise((resolve, reject) => {
axios({
url,
method,
params,
baseURL,
headers,
data,
withCredentials: true,
responseType,
validateStatus: function (status: number) {
return status >= 200 && status < 300;
},
})
.then((response: AxiosResponse) => {
resolve(response.data);
})
.catch((error: AxiosError) => {
reject(error.response);
});
});
};
import { ajax } from "@/api/ajax";
import { paramsSerialize } from "@/api/serialize";
import { AjaxRes } from "@/types/common";
export const ajaxGet = (url: string, params = {}): Promise<AjaxRes> => ajax({ method: "get", url, params });
export const ajaxDelete = (url: string, params = {}, data = {}): Promise<AjaxRes> => ajax({ method: "delete", url, params, data });
export const ajaxPost = (url: string, params = {}, data = {}, paramsSerialization = false): Promise<AjaxRes> =>
ajax({
method: "post",
url,
params,
data: paramsSerialize(paramsSerialization, data),
headers: {
"Content-Type": paramsSerialization ? "application/x-www-form-urlencoded;charset=UTF-8" : "application/json;charset=UTF-8",
},
});
export const ajaxPut = (url: string, data = {}, paramsSerialization = false, params = {}): Promise<AjaxRes> =>
ajax({
method: "put",
url,
params,
data: paramsSerialize(paramsSerialization, data),
headers: {
"Content-Type": paramsSerialization ? "application/x-www-form-urlencoded;charset=UTF-8" : "application/json;charset=UTF-8",
},
});
export const ajaxPatch = (url: string, data = {}, paramsSerialization = false, params = {}): Promise<AjaxRes> =>
ajax({
method: "patch",
url,
params,
data: paramsSerialize(paramsSerialization, data),
headers: {
"Content-Type": paramsSerialization ? "application/x-www-form-urlencoded;charset=UTF-8" : "application/json;charset=UTF-8",
},
});
import qs from "qs";
export const paramsSerialize = (paramsSerialization: boolean, data: Record<string, unknown>) => (paramsSerialization ? qs.stringify(data) : data);
export interface AjaxRes {
code: number;
data: any | null;
success: boolean;
timestamp: string;
message: string;
}