import { Config } from '@backstage/config' ; import { fetch } from 'cross-fetch' ; import { Logger } from 'winston' ; import { HttpOptions } from './types' ; class HttpError extends Error { } export const generateBackstageUrl = ( config , path ) : string => { const externalUrl = config . getOptionalString ( 'backend.baseUrl' ) || '' ; if ( externalUrl === '' ) { throw new Error ( 'Unable to get base url' ) ; } return externalUrl + path ; } ; export const http = async ( options , logger ) : Promise < any > => { let res ; const { url , ... other } = options ; try { res = await fetch ( url , other ) ; } catch ( e ) { throw new HttpError ( `There was an issue with the request: ${ e }` ) ; } if ( res . status >= 400 ) { logger . error ( `There was an issue with your request. Status code: ${ res . status }` ) ; throw new HttpError ( 'Unable to complete request' ) ; } const headers = { } ; for ( const [ name , value ] of res . headers ) { headers [ name ] = value ; } try { const body = headers [ 'content-type' ] && headers [ 'content-type' ] . includes ( 'application/json' ) ? await res . json ( ) : { message : await res . text ( ) } ; return { code : res . status , headers , body } ; } catch ( e ) { throw new HttpError ( `Could not get response: ${ e }` ) ; } } ;