import 'cross-fetch/polyfill' ; import { Config , EnqueuedTask } from '../types' ; import { httpResponseErrorHandler , httpErrorHandler } from '../errors' ; class HttpRequests { headers : Record < string , any > ; url : URL ; constructor ( config ) { this . headers = Object . assign ( { } , config . headers || { } ) ; this . headers [ 'Content-Type' ] = 'application/json' ; if ( config . apiKey ) { this . headers [ 'Authorization' ] = `Bearer ${ config . apiKey }` ; } this . url = new URL ( config . host ) ; } static addTrailingSlash ( url ) { if ( ! url . endsWith ( '/' ) ) { url += '/' ; } return url ; } async request ( { method , url , params , body , config , } ) { const constructURL = new URL ( url , this . url ) ; if ( params ) { const queryParams = new URLSearchParams ( ) ; Object . keys ( params ) . filter ( ( x ) => params [ x ] !== null ) . map ( ( x ) => queryParams . set ( x , params [ x ] ) ) ; constructURL . search = queryParams . toString ( ) ; } try { const response = await fetch ( constructURL . toString ( ) , { ... config , method , body : JSON . stringify ( body ) , headers : this . headers } ) . then ( ( res ) => httpResponseErrorHandler ( res ) ) ; const parsedBody = await response . text ( ) ; try { const parsedJson = JSON . parse ( parsedBody ) ; return parsedJson ; } catch ( _ ) { return ; } } catch ( e ) { const stack = e . stack ; httpErrorHandler ( e , stack , constructURL . toString ( ) ) ; } } async get ( url , params ? , config ? ) ; async get < T = any > ( url , params ? , config ? ) ; async get ( url , params ? , config ? ) { return await this . request ( { method : 'GET' , url , params , config } ) ; } async post < T = any , R = EnqueuedTask > ( url , data ? , params ? , config ? ) ; async post ( url , data ? , params ? , config ? ) { return await this . request ( { method : 'POST' , url , body : data , params , config } ) ; } async put < T = any , R = EnqueuedTask > ( url , data ? , params ? , config ? ) ; async put ( url , data ? , params ? , config ? ) { return await this . request ( { method : 'PUT' , url , body : data , params , config } ) ; } async patch ( url , data ? , params ? , config ? ) { return await this . request ( { method : 'PATCH' , url , body : data , params , config } ) ; } async delete ( url , data ? , params ? , config ? ) ; async delete < T > ( url , data ? , params ? , config ? ) ; async delete ( url , data ? , params ? , config ? ) { return await this . request ( { method : 'DELETE' , url , body : data , params , config } ) ; } } export { HttpRequests } ;