import axios , { AxiosRequestConfig , AxiosInstance , AxiosResponse } from 'axios' ; import { Provide , Inject , Init , Config , App } from '@midwayjs/decorator' ; import { IMidwayApplication } from '@midwayjs/core' ; import { AXIOS_INSTANCE_KEY , AxiosHttpService } from './interface' ; @ Provide ( ) export class HttpService implements AxiosHttpService { private instance : AxiosInstance ; @ Inject ( ) protected ctx : any ; @ App ( ) protected app : IMidwayApplication ; @ Config ( 'axios' ) protected httpConfig : AxiosRequestConfig ; get interceptors ( ) { return this . instance . interceptors ; } @ Init ( ) protected async init ( ) { if ( ! this . app . getApplicationContext ( ) . registry . hasObject ( AXIOS_INSTANCE_KEY ) ) { const instance = axios . create ( this . httpConfig ?? { } ) ; instance . interceptors . request . use ( config => { return config ; } , error => { return Promise . reject ( error ) ; } ) ; instance . interceptors . response . use ( response => { return response ; } , error => { return Promise . reject ( error ) ; } ) ; this . app . getApplicationContext ( ) . registry . registerObject ( AXIOS_INSTANCE_KEY , instance ) ; } this . instance = this . app . getApplicationContext ( ) . registry . getObject ( AXIOS_INSTANCE_KEY ) ; } getUri ( config ? ) { return this . instance . getUri ( config ) ; } request < T = any , R = AxiosResponse < T > > ( config ) { return this . instance . request ( config ) ; } get < T = any , R = AxiosResponse < T > > ( url , config ? ) { return this . instance . get ( url , config ) ; } delete < T = any , R = AxiosResponse < T > > ( url , config ? ) { return this . instance . delete ( url , config ) ; } head < T = any , R = AxiosResponse < T > > ( url , config ? ) { return this . instance . head ( url , config ) ; } options < T = any , R = AxiosResponse < T > > ( url , config ? ) { return this . instance . options ( url , config ) ; } post < T = any , R = AxiosResponse < T > > ( url , data ? , config ? ) { return this . instance . post ( url , data , config ) ; } put < T = any , R = AxiosResponse < T > > ( url , data ? , config ? ) { return this . instance . put ( url , data , config ) ; } patch < T = any , R = AxiosResponse < T > > ( url , data ? , config ? ) { return this . instance . patch ( url , data , config ) ; } }