import * as http from "http" ; import * as https from "https" ; import axios , { AxiosInstance , AxiosRequestConfig } from "axios" ; import { getVersion } from "./metadata" ; import { HTTPMethod , RequestOptions , Response } from "./requests" ; /**
 * The default Request Client used by the SDK if customer does not
 * provide their own client.
 */ export class HTTPClient implements IRequestClient { public defaultTimeout = 15000 ; public readonly defaultHeaders = { "content-type" : "application/json" , "user-agent" : `connect-sdk-js/${ getVersion ( ) }` , } ; private axios : AxiosInstance ; public constructor ( conf ? ) { this . axios = this . initAxios ( conf ) ; } public async request ( method , url , opts ) { const requestCfg = { method , url , timeout : opts . timeout , data : opts . data , params : opts . params , headers : Object . assign ( { } , this . defaultHeaders , opts . headers , { authorization : `Bearer ${ opts . authToken }` , } ) , } as AxiosRequestConfig ; const response = await this . axios . request ( requestCfg ) ; return { status : response . status , data : response . data } as Response ; } param { ClientConfig } conf private initAxios ( conf ) { conf = conf || { } ; const axiosConfig = { timeout : conf . timeout || this . defaultTimeout , headers : this . defaultHeaders , } as AxiosRequestConfig ; if ( conf . keepAlive ) { axiosConfig . httpsAgent = new https . Agent ( { keepAlive : true } ) ; axiosConfig . httpAgent = new http . Agent ( { keepAlive : true } ) ; } const axiosInstance = axios . create ( axiosConfig ) ; axiosInstance . interceptors . response . use ( ( response ) => response , ( error ) => { if ( error . response && error . response . data ) { return Promise . reject ( error . response . data ) ; } else { return Promise . reject ( error ) ; } } ) ; return axiosInstance ; } } export interface IRequestClient { defaultTimeout : number ; param { HTTPMethod } method param { string } url param { ClientRequestOptions } opts returns { Promise < Response > } request ( method , url , opts ) : Promise < Response > ; } export interface ClientConfig { keepAlive ? : boolean ; timeout ? : number ; } export interface ClientRequestOptions extends RequestOptions { authToken : string ; }