1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| import { request as umiRequest } from 'umi'; import { RequestOptionsInit, RequestResponse } from 'umi-request';
interface extendedRequestOptions { skipErrorHandler?: boolean; withToken?: boolean; showError?: boolean; }
interface RequestOptions extends RequestOptionsInit, extendedRequestOptions {}
interface RequestOptionsWithResponse extends RequestOptionsInit, extendedRequestOptions { getResponse: true; }
interface RequestOptionsWithoutResponse extends RequestOptionsInit, extendedRequestOptions { getResponse: false; }
export interface ResponseResult<T> { data: T; code: string; desc: string; }
interface RequestMethod<R = false> { <T = any>(url: string, options: RequestOptionsWithResponse): Promise<RequestResponse<ResponseResult<T>>>; <T = any>(url: string, options: RequestOptionsWithoutResponse): Promise<ResponseResult<T>>; <T = any>(url: string, options?: RequestOptions): R extends true ? Promise<RequestResponse<ResponseResult<T>>> : Promise<ResponseResult<T>>; }
const request: RequestMethod = async (url: any, options: any = {}) => { const { withToken = true, showError = true, headers, ...restOptions } = options as RequestOptions; let newHeaders: Record<string, string> = {}; if (withToken) { const token = getToken(); newHeaders['Authorization'] = `Bearer ${token}`; }
const newOptions: RequestOptions = { ...restOptions, headers: { ...headers, ...newHeaders }, };
return umiRequest(url, newOptions).catch(err => { showError && console.error(err); }); };
export default request;
|