forked from mengyxu/noob-components
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
323 lines
8.2 KiB
323 lines
8.2 KiB
/* eslint-disable */ |
|
import axios from "axios"; |
|
import * as Lang from "../i18n"; |
|
import { loading, close, showMessage } from "../element"; |
|
const { t } = Lang.i18n; |
|
|
|
let router; |
|
|
|
const config = { |
|
baseURL: process.env.VUE_APP_BASE_URL ? "/api" : "", |
|
timeout: 60 * 1000, |
|
withCredentials: true, // Check cross-site Access-Control |
|
}; |
|
|
|
const _axios = axios.create(config); |
|
_axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8"; |
|
_axios.defaults.headers.put["Content-Type"] = "application/json;charset=UTF-8"; |
|
_axios.defaults.headers.delete["Content-Type"] = "application/json;charset=UTF-8"; |
|
|
|
export const registerBaseUrl = (url) => { |
|
_axios.defaults.baseURL = url; |
|
}; |
|
|
|
export const registerRouter = (routerP) => { |
|
router = routerP; |
|
}; |
|
|
|
// Add a request interceptor |
|
_axios.interceptors.request.use( |
|
function (config) { |
|
const time = new Date().getTime().toString(); |
|
const params = new URLSearchParams(config.params); |
|
if (params.toString()) { |
|
delEmpty(params); |
|
params.append("t", time); |
|
config.params = params; |
|
} |
|
const data = config.data; |
|
if (data != null && typeof data === "object") { |
|
delEmpty(data); |
|
data.t = time; |
|
} |
|
return config; |
|
}, |
|
function (error) { |
|
return Promise.reject(error); |
|
} |
|
); |
|
|
|
function delEmpty(data) { |
|
if (data && data instanceof URLSearchParams) { |
|
for (const [k, v] of data.entries()) { |
|
if (!v) data.delete(k); |
|
} |
|
} else if (data && typeof data === "object") { |
|
for (const item in data) { |
|
if (data.hasOwnProperty(item)) { |
|
const val = data[item]; |
|
if ((val == null || val == "null" || val == "") && val !== 0 && val !== false) { |
|
delete data[item]; |
|
} |
|
} |
|
} |
|
} |
|
} |
|
|
|
// Add a response interceptor |
|
_axios.interceptors.response.use( |
|
function (response) { |
|
return response.data; |
|
}, |
|
function (error) { |
|
return Promise.reject(error); |
|
} |
|
); |
|
|
|
type QueryParams = URLSearchParams | Record<string, any> | ConstructorParameters<typeof URLSearchParams>[0]; |
|
|
|
export interface AxiosOptions { |
|
noMsg?: boolean | null; |
|
noLoading?: boolean | null; |
|
filter?: (response) => any; |
|
query?: QueryParams; |
|
} |
|
|
|
const defaultFilterResp = (resp) => { |
|
const isSuccess = resp.success || resp.status === "ok" || resp.status === "success" || resp.data != null; |
|
const isError = resp.success === false || resp.status === "error"; |
|
if (isSuccess) { |
|
return resp.data ? resp.data : resp; |
|
} else if (isError) { |
|
return false; |
|
} else return resp; |
|
}; |
|
|
|
export function post(url, data?, options: AxiosOptions = {}) { |
|
return new Promise((resolve, reject) => { |
|
if (!options.noLoading) { |
|
loading(); |
|
} |
|
_axios.post(url, data).then( |
|
(response: any) => { |
|
handResponse(response, resolve, options); |
|
}, |
|
(err) => { |
|
handError(err, reject, options); |
|
} |
|
); |
|
}); |
|
} |
|
|
|
function mergeQueryParams(...params: Array<QueryParams>) { |
|
const res: URLSearchParams = new URLSearchParams(); |
|
for (const param of params) { |
|
if (param == null) continue; |
|
let parsed; |
|
if (param instanceof URLSearchParams) { |
|
parsed = param; |
|
} else { |
|
parsed = new URLSearchParams(param); |
|
} |
|
|
|
parsed |
|
.entries() |
|
.filter(([k, v]) => v != null && v != "null" && v != "undefined" && v != "") |
|
.forEach(([k, v]) => res?.append(k, v)); |
|
} |
|
|
|
return res ?? new URLSearchParams(); |
|
} |
|
|
|
export function get(url, data?: QueryParams, options: AxiosOptions = {}) { |
|
return new Promise((resolve, reject) => { |
|
if (!options.noLoading) { |
|
loading(); |
|
} |
|
_axios.get(url, { params: mergeQueryParams(data, options.query) }).then( |
|
(response: any) => { |
|
handResponse(response, resolve, options); |
|
}, |
|
(err) => { |
|
handError(err, reject, options); |
|
} |
|
); |
|
}); |
|
} |
|
|
|
export function put(url, data?, options: AxiosOptions = {}) { |
|
return new Promise((resolve, reject) => { |
|
if (!options.noLoading) { |
|
loading(); |
|
} |
|
_axios.put(url, data, { params: mergeQueryParams(options.query) }).then( |
|
(response: any) => { |
|
handResponse(response, resolve, options); |
|
}, |
|
(err) => { |
|
handError(err, reject, options); |
|
} |
|
); |
|
}); |
|
} |
|
|
|
export function delate(url, data?, options: AxiosOptions = {}) { |
|
return new Promise((resolve, reject) => { |
|
if (!options.noLoading) { |
|
loading(); |
|
} |
|
_axios({ |
|
method: "delete", |
|
url: url, |
|
data: data, |
|
params: mergeQueryParams(options.query), |
|
}).then( |
|
(response: any) => { |
|
handResponse(response, resolve, options); |
|
}, |
|
(err) => { |
|
handError(err, reject, options); |
|
} |
|
); |
|
}); |
|
} |
|
|
|
function handResponse(response, resolve, options: AxiosOptions = {}) { |
|
if (!options.noLoading) { |
|
close(); |
|
} |
|
|
|
const filterResponse = options.filter ?? defaultFilterResp; |
|
const result = filterResponse(response); |
|
|
|
if (result) { |
|
if (!options.noMsg && response.message) { |
|
showMessage("success", response.message); |
|
} |
|
|
|
resolve(result); |
|
} else { |
|
if (response.message == "session timeout") { |
|
router?.push("/login"); |
|
response.message = t("http.unLogin"); |
|
} |
|
if (response.message == "no permission") { |
|
response.message = t("http.unPermission"); |
|
} |
|
if (response.message?.indexOf("no permission for ") == 0) { |
|
response.message = t("http.noPermission"); |
|
} |
|
if (!options.noMsg && response.message) { |
|
showMessage("error", response.message); |
|
} |
|
response.error && console.log(response.error); |
|
resolve(false); |
|
} |
|
} |
|
|
|
function handError(err, reject, options: AxiosOptions = {}) { |
|
if (!options.noLoading) { |
|
close(); |
|
} |
|
if (!options.noMsg) { |
|
showMessage("error", t("http.error")); |
|
} |
|
reject(err); |
|
} |
|
|
|
export function upload(file, url, data) { |
|
return new Promise((resolve, reject) => { |
|
let param = new FormData(); // 创建form对象 |
|
param.append("file", file); // 通过append向form对象添加数据 |
|
if (data) { |
|
for (const item in data) { |
|
if (data.hasOwnProperty(item)) { |
|
param.append(item, data[item]); // 添加form表单中其他数据 |
|
} |
|
} |
|
} |
|
let config = { |
|
headers: { "Content-Type": "multipart/form-data" }, |
|
}; |
|
_axios.post(url, param, config).then( |
|
(response) => { |
|
handResponse(response, resolve); |
|
}, |
|
(err) => { |
|
handError(err, reject); |
|
} |
|
); |
|
}); |
|
} |
|
|
|
export function getFile(url, data?, options: AxiosOptions = {}) { |
|
return new Promise((resolve, reject) => { |
|
if (!options.noLoading) { |
|
loading(); |
|
} |
|
_axios({ |
|
method: "get", |
|
url: url, // 请求地址 |
|
params: data, // 参数 |
|
responseType: "blob", // 表明返回服务器返回的数据类型 |
|
}).then( |
|
(response: any) => { |
|
handResponse(response, resolve, options); |
|
}, |
|
(err) => { |
|
handError(err, reject, options); |
|
} |
|
); |
|
}); |
|
} |
|
|
|
export function download(fileName, url, data = {}, callBack?) { |
|
loading(); |
|
_axios({ |
|
method: "get", |
|
url: url, // 请求地址 |
|
params: data, // 参数 |
|
responseType: "blob", // 表明返回服务器返回的数据类型 |
|
}).then( |
|
(response: any) => { |
|
close(); |
|
const reader = new FileReader() as any; |
|
reader.readAsText(response); |
|
reader.onload = function () { |
|
try { |
|
const result = JSON.parse(reader.result); |
|
if (typeof result === "object") { |
|
showMessage("error", result.message, false); |
|
if (callBack != null) { |
|
callBack(false); |
|
} |
|
return; |
|
} |
|
} catch (err) {} |
|
const blob = new Blob([response], { |
|
type: "application/octet-stream", |
|
}); |
|
const navigator = window.navigator as any; |
|
if (navigator.msSaveOrOpenBlob) { |
|
navigator.msSaveBlob(blob, fileName); |
|
} else { |
|
const link = document.createElement("a"); |
|
link.href = window.URL.createObjectURL(blob); |
|
link.download = fileName; |
|
link.click(); |
|
window.URL.revokeObjectURL(link.href); |
|
} |
|
if (callBack != null) { |
|
callBack(true); |
|
} |
|
}; |
|
}, |
|
(err) => { |
|
close(); |
|
showMessage("error", t("http.downFail")); |
|
if (callBack != null) { |
|
callBack(false); |
|
} |
|
} |
|
); |
|
}
|
|
|