import debug from "debug" ; import { CreateResponse , ISerializedResponse , OnSerializedRequest , } from "unmock-core/dist/interfaces" ; import { Fetch } from "." ; import serialize from "./serialize" ; import { Response } from "./types" ; const debugLog = debug ( "unmock:fetch-mitm" ) ; const isCreateResponse = ( cb ) : cb is CreateResponse => cb . length === 1 ; export const buildFetch = ( cb ) : Fetch => function fetch ( url , init ? ) : Promise < Response > { const req = serialize ( url , init ) ; debugLog ( `Serialized request: ${ JSON . stringify ( req ) }, init: ${ init }` ) ; return new Promise ( ( resolve , reject ) => { const sendResponse = ( res ) : void => { const responseInit = { status : res . statusCode } ; resolve ( new Response ( res . body , responseInit ) ) ; } ; const emitError = ( e ) => reject ( e ) ; setTimeout ( ( ) => { if ( isCreateResponse ( cb ) ) { try { const res = cb ( req ) ; sendResponse ( res ) ; } catch ( err ) { reject ( err ) ; } } else { cb ( req , sendResponse , emitError ) ; } } , 0 ) ; } ) ; } ; export default buildFetch ;