mirror of https://github.com/msgbyte/tailchat
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
72 lines
1.7 KiB
TypeScript
72 lines
1.7 KiB
TypeScript
4 years ago
|
import axios, { AxiosRequestConfig } from 'axios';
|
||
4 years ago
|
import _get from 'lodash/get';
|
||
|
import _isFunction from 'lodash/isFunction';
|
||
|
import { getErrorHook, tokenGetter } from '../manager/request';
|
||
4 years ago
|
import { getServiceUrl, onServiceUrlChange } from '../manager/service';
|
||
4 years ago
|
|
||
|
export type CommonRequestResult<T> =
|
||
|
| ({
|
||
|
result: false;
|
||
|
msg: string;
|
||
|
} & Partial<T>) // 并上一个T是为了方便取值, 但需要判定
|
||
|
| ({
|
||
|
result: true;
|
||
|
} & T);
|
||
|
|
||
|
class RequestError extends Error {}
|
||
|
|
||
4 years ago
|
export type RequestConfig = AxiosRequestConfig;
|
||
|
|
||
4 years ago
|
/**
|
||
|
* 创建请求实例
|
||
|
*/
|
||
|
export function createRequest() {
|
||
|
const ins = axios.create({
|
||
4 years ago
|
baseURL: getServiceUrl(),
|
||
4 years ago
|
});
|
||
4 years ago
|
onServiceUrlChange((getUrl) => {
|
||
|
// 重置请求地址
|
||
|
ins.defaults.baseURL = getUrl();
|
||
|
});
|
||
4 years ago
|
|
||
|
ins.interceptors.request.use(async (val) => {
|
||
|
if (
|
||
|
['post', 'get'].includes(String(val.method).toLowerCase()) &&
|
||
|
!val.headers['X-Token']
|
||
|
) {
|
||
|
// 任何请求都尝试增加token
|
||
|
val.headers['X-Token'] = await tokenGetter();
|
||
|
}
|
||
|
|
||
|
return val;
|
||
|
});
|
||
|
|
||
|
ins.interceptors.response.use(
|
||
|
(val) => {
|
||
4 years ago
|
/**
|
||
|
* 预处理返回的数据
|
||
|
*/
|
||
|
val.data = _get(val.data, 'data', val.data);
|
||
|
|
||
4 years ago
|
return val;
|
||
|
},
|
||
|
(err) => {
|
||
|
// 尝试获取错误信息
|
||
|
const errorMsg: string = _get(err, 'response.data.message');
|
||
|
const code: number = _get(err, 'response.data.code');
|
||
|
if (_isFunction(getErrorHook)) {
|
||
|
const isContinue = getErrorHook(err);
|
||
|
if (isContinue === false) {
|
||
|
return { data: { result: false, msg: errorMsg, code } };
|
||
|
}
|
||
|
}
|
||
|
|
||
|
throw new RequestError(errorMsg ?? err.message);
|
||
|
}
|
||
|
);
|
||
|
|
||
|
return ins;
|
||
|
}
|
||
|
|
||
|
export const request = createRequest();
|