Reinit project

This commit is contained in:
Limo Saplf
2019-08-31 20:44:15 +08:00
commit b51ae824c7
115 changed files with 20955 additions and 0 deletions

86
src/utils/http.ts Normal file
View File

@@ -0,0 +1,86 @@
import axios, { AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios';
import { formatMessage } from 'umi-plugin-locale';
import _ from 'lodash';
import { globalState } from '@/services/common';
import { isDev } from './utils';
export interface AppResp<T = any> {
ok: boolean,
code: number;
msg: string;
data?: T;
}
const successLabel = 'color:white;background-color:green;padding: 1px 2px';
const failureLabel = 'color:white;background-color:red;padding: 1px 2px';
const originLabel = 'color:unset;background-color:unset;padding:unset';
const baseURL = 'http://yapi.faronear.org/mock/35';
const instance = axios.create({
baseURL,
});
async function filter<T>(
method: keyof AxiosInstance,
...args: any[]
): Promise<AppResp<T>> {
let ret;
try {
const { user } = globalState().user;
if (user && user.token) {
instance.defaults.headers = {
...instance(instance.defaults.headers),
Authorization: user.token,
};
} else {
instance.defaults.headers = _.omit(instance.defaults.headers, 'Authorization');
}
const { status, data } = await (instance[method] as (...args: any[]) => Promise<AxiosResponse<AppResp>>)(...args);
ret = {
ok: status >= 200 && status < 300 && data && data.code === 0,
code: data && data.code,
msg: data && data.msg,
data: data && data.data,
};
} catch (e) {
ret = {
ok: false,
msg: formatMessage({ id: 'network.error' }),
code: 404,
};
}
if (isDev) {
/* tslint:disable */
console.group(`%c${method.toUpperCase()}%c: ${baseURL}${args[0]}`, ret.ok ? successLabel : failureLabel, originLabel);
console.log(ret);
console.groupEnd();
/* tslint:enable */
}
return ret;
}
function groupUrl(url: string, params?: any): string {
const postfix = _.keys(params || {})
.map(key => `${key}=${encodeURIComponent(params[key]) || ''}`)
.join('&');
if (!postfix) return url;
return `${url}?${postfix}`;
}
function get<T = any>(url: string, params?: any, config?: AxiosRequestConfig) {
return filter<T>('get', groupUrl(url, params), config);
}
function post<T = any>(url: string, data?: any, config?: AxiosRequestConfig) {
return filter<T>('post', url, data, config);
}
export default {
get,
post,
};
export {
get,
post,
};