import { RequestParams , Method , ContentType } from './type' ; import axios , { AxiosInstance , AxiosRequestConfig } from 'axios' ; import { Convert } from './json2Model' ; import DuplicateRequest from './duplicate' ; import qs from 'qs' ; export * from './type' ; export interface HttpClientConfig extends AxiosRequestConfig { defaultParams ? : RequestParams ; log ? : boolean ; checkQuickClick ? : boolean ; clickInterval ? : number ; } export default class HttpClient { public defaultConfig : HttpClientConfig ; public httpClient : AxiosInstance ; constructor ( options = { } ) { this . httpClient = axios . create ( options ) ; this . defaultConfig = options ; } description param { Method } method param { APIPath } path param { RequestParams } params param { ContentType } contentType param { RequestOptions } optionsSource return { * } async request < T > ( path = '' , method = Method . GET , params ? , contentType = ContentType . json , optionsSource ? ) { const options = Object . assign ( { } , this . defaultConfig , optionsSource ) ; const { headers , clickInterval } = options ; headers [ 'Content-type' ] = contentType ; const allParams = Object . assign ( { } , this . defaultConfig . defaultParams , params ) ; const requestConfig = { url : `${ path }` , method , headers , } ; if ( options . checkQuickClick === true && DuplicateRequest . hashUrlAndParams ( requestConfig . url ?? '' , method , allParams , clickInterval ) ) { options . log && console . log ( 'click quick' ) ; return null ; } if ( method === Method . GET ) { requestConfig . params = allParams ; } else { if ( contentType === ContentType . form ) { requestConfig . data = qs . stringify ( allParams ) ; } else { requestConfig . data = JSON . stringify ( allParams ) ; } } return this . httpClient . request ( requestConfig ) . then ( res => { options . log && console . log ( res ) ; const data = JSON . stringify ( res . data ) ; if ( res . status >= 200 && res . status < 300 ) { return Convert . jsonToModel ( data ) as T ; } else { return Promise . reject ( data ) ; } } ) . catch ( async ( error ) => { return Promise . reject ( error ) ; } ) ; } }