import getStream from 'get-stream' ; import type { Client } from 'undici' ; import { Pool } from 'undici' ; import type { URL } from 'url' ; export type Result < R > = { statusCode : Client . ResponseData [ 'statusCode' ] ; headers : Client . ResponseData [ 'headers' ] ; data : R ; } ; param pool function assertHasPool < A > ( pool ) { if ( pool === undefined ) { throw new Error ( 'Connection has not been opened' ) ; } } /**
 * Open an HTTP connection pool
 */ export class Connection { private _pool : Pool | undefined ; constructor ( ) { } param response param handler returns static async onHttpError < R , HR > ( response , handler ) { const _response = await response ; if ( _response . statusCode >= 400 ) { return handler ( _response ) ; } return _response ; } param url param options returns open ( url , options ? ) { if ( this . _pool ) return ; this . _pool = new Pool ( url , { connections : 1000 , keepAliveMaxTimeout : 600e3 , headersTimeout : 0 , ... options , } ) ; } param method param endpoint param headers param body returns async raw < R > ( method , endpoint , headers ? , body ? ) { assertHasPool ( this . _pool ) ; const response = await this . _pool . request ( { path : endpoint , method : method , headers : { 'Content-Type' : 'application/json' , ... headers , } , body , bodyTimeout : 0 , } ) ; const result = { statusCode : response . statusCode , headers : response . headers , data : JSON . parse ( await getStream ( response . body ) ) as R , } ; return result ; } param endpoint param body param headers returns post < R > ( endpoint , body ? , headers ? ) { return this . raw < R > ( 'POST' , endpoint , headers , body ) ; } param endpoint param body param headers returns get < R > ( path , headers ? ) { return this . raw < R > ( 'GET' , path , headers ) ; } /**
     * Close the connections
     */ close ( ) { if ( this . _pool ) { this . _pool . close ( ( ) => { } ) ; } this . _pool = undefined ; } }