import { GaxiosError , GaxiosOptions , GaxiosPromise , GaxiosResponse , request , } from 'gaxios' ; import { validate } from './options' ; const pkg = require ( '../../package.json' ) ; const PRODUCT_NAME = 'google-api-nodejs-client' ; export interface Transporter { request < T > ( opts ) : GaxiosPromise < T > ; request < T > ( opts , callback ? ) : void ; request < T > ( opts , callback ? ) : GaxiosPromise | void ; } export interface BodyResponseCallback < T > { ( err , res ? ) : void ; } export interface RequestError extends GaxiosError { errors : Error [ ] ; } export class DefaultTransporter { /**
     * Default user agent.
     */ static readonly USER_AGENT = `${ PRODUCT_NAME }/${ pkg . version }` ; param opts return configure ( opts = { } ) { opts . headers = opts . headers || { } ; if ( typeof window === 'undefined' ) { const uaValue = opts . headers [ 'User-Agent' ] ; if ( ! uaValue ) { opts . headers [ 'User-Agent' ] = DefaultTransporter . USER_AGENT ; } else if ( ! uaValue . includes ( `${ PRODUCT_NAME }/` ) ) { opts . headers [ 'User-Agent' ] = `${ uaValue } ${ DefaultTransporter . USER_AGENT }` ; } const authVersion = `auth/${ pkg . version }` ; if ( opts . headers [ 'x-goog-api-client' ] && ! opts . headers [ 'x-goog-api-client' ] . includes ( authVersion ) ) { opts . headers [ 'x-goog-api-client' ] = `${ opts . headers [ 'x-goog-api-client' ] } ${ authVersion }` ; } else if ( ! opts . headers [ 'x-goog-api-client' ] ) { const nodeVersion = process . version . replace ( /^v/ , '' ) ; opts . headers [ 'x-goog-api-client' ] = `gl-node/${ nodeVersion } ${ authVersion }` ; } } return opts ; } param opts param callback return request < T > ( opts ) ; request < T > ( opts , callback ? ) ; request < T > ( opts , callback ? ) { opts = this . configure ( opts ) ; try { validate ( opts ) ; } catch ( e ) { if ( callback ) { return callback ( e ) ; } else { throw e ; } } if ( callback ) { request < T > ( opts ) . then ( r => { callback ( null , r ) ; } , e => { callback ( this . processError ( e ) ) ; } ) ; } else { return request < T > ( opts ) . catch ( e => { throw this . processError ( e ) ; } ) ; } } /**
     * Changes the error to include details from the body.
     */ private processError ( e ) { const res = e . response ; const err = e as RequestError ; const body = res ? res . data : null ; if ( res && body && body . error && res . status !== 200 ) { if ( typeof body . error === 'string' ) { err . message = body . error ; err . code = res . status . toString ( ) ; } else if ( Array . isArray ( body . error . errors ) ) { err . message = body . error . errors . map ( ( err2 ) => err2 . message ) . join ( '\n' ) ; err . code = body . error . code ; err . errors = body . error . errors ; } else { err . message = body . error . message ; err . code = body . error . code || res . status ; } } else if ( res && res . status >= 400 ) { err . message = body ; err . code = res . status . toString ( ) ; } return err ; } }