import fetch from 'isomorphic-unfetch' ; import { name , version } from '../../../package.json' ; import { BAD_REQUEST , UNAUTHORIZED , FORBIDDEN , NOT_FOUND , TOO_MANY_REQUESTS , } from './responses' ; import type { ApiData , ErrorData } from './types' ; function blockedWithRayId ( rayId ) { return `Request blocked, contact haveibeenpwned.com if this continues (Ray ID: ${ rayId })` ; } internal private param { string } endpoint param options param { string } options . apiKey param { string } options . baseUrl param { string } options . userAgent returns { Promise < ApiData > } export function fetchFromApi ( endpoint , { apiKey , baseUrl = 'https://haveibeenpwned.com/api/v3' , userAgent , } = { } ) { const headers = { } ; if ( apiKey ) { headers [ 'HIBP-API-Key' ] = apiKey ; } if ( userAgent ) { headers [ 'User-Agent' ] = userAgent ; } if ( ! userAgent && typeof navigator === 'undefined' ) { headers [ 'User-Agent' ] = `${ name } ${ version }` ; } const config = { headers } ; const url = `${ baseUrl . replace ( /\/$/g , '' ) }${ endpoint }` ; return fetch ( url , config ) . then ( ( res ) => { if ( res . ok ) return res . json ( ) ; switch ( res . status ) { case BAD_REQUEST . status : throw new Error ( BAD_REQUEST . statusText ) ; case UNAUTHORIZED . status : return res . json ( ) . then ( ( body ) => { throw new Error ( body . message ) ; } ) ; case FORBIDDEN . status : { const rayId = res . headers . get ( 'cf-ray' ) ; if ( rayId ) { throw new Error ( blockedWithRayId ( rayId ) ) ; } throw new Error ( FORBIDDEN . statusText ) ; } case NOT_FOUND . status : return null ; case TOO_MANY_REQUESTS . status : return res . json ( ) . then ( ( body ) => { throw new Error ( body . message ) ; } ) ; default : throw new Error ( res . statusText ) ; } } ) ; }