import axios , { AxiosResponse , AxiosRequestConfig } from 'axios' ; import config from '@shared/project.config' ; import _get from 'lodash/get' ; import _isString from 'lodash/isString' ; import _isNil from 'lodash/isNil' ; import _isFunction from 'lodash/isFunction' ; import { getErrorHook , tokenGetter } from '@shared/manager/request' ; import { errorCode } from './error' ; import { showLimitedToasts } from './ui' ; const fileUrl = config . file . url ; interface CommonResp { result : string ; msg ? : string ; } deprecated export default async function requestOld < T = any > ( path , method = 'get' , data ? , options ? ) { const ext = { } ; if ( method === 'get' ) { ext . params = data ; } else if ( method === 'post' ) { ext . data = data ; } const res = await axios ( { url : fileUrl + path , method , ... options , ... ext , } ) ; return res ; } export type CommonRequestResult < T > = ( { result : false ; msg : string ; } & Partial < T > ) | ( { result : true ; } & T ) ; /**
 * 创建请求实例
 */ export function createRequest ( ) { const ins = axios . create ( { baseURL : config . url . api , } ) ; ins . interceptors . request . use ( async ( val ) => { if ( [ 'post' , 'get' ] . includes ( String ( val . method ) . toLowerCase ( ) ) && ! val . headers [ 'X-Token' ] ) { val . headers [ 'X-Token' ] = await tokenGetter ( ) ; } return val ; } ) ; ins . interceptors . response . use ( ( val ) => { return val ; } , ( err ) => { const errorMsg = _get ( err , 'response.data.msg' ) ; const code = _get ( err , 'response.data.code' ) ; if ( _isFunction ( getErrorHook ) ) { const isContinue = getErrorHook ( err ) ; if ( isContinue === false ) { return { data : { result : false , msg : errorMsg , code } } ; } } if ( ! _isNil ( code ) ) { if ( code === errorCode . LIMITED ) { showLimitedToasts ( ) ; } } throw errorMsg ?? err ; } ) ; return ins ; } export const request = createRequest ( ) ;