import axios from 'axios' ; import { cancellableMethods } from '../../constants' ; import { Cancellation } from '../../service/worker/runtime/typings' ; import { MiddlewareContext } from '../typings' ; const production = process . env . VTEX_PRODUCTION === 'true' ; const handleCancellation = ( ctx , cancellation ) => { let cancellable = true ; return { cancelToken : new axios . CancelToken ( ( canceller ) => { cancellation . source . token . promise . then ( cancel => { if ( cancellable ) { canceller ( cancel . message ) ; } } ) ; } ) , onRequestFinish : ( ) => { if ( ! ctx . config . cancelToken ) { cancellable = false ; } else if ( ! ctx . response ) { cancellable = true ; } else if ( ctx . config . responseType !== 'stream' ) { cancellable = false ; } else if ( ctx . response . data . readableEnded ) { cancellable = false ; } else { ctx . response . data . on ( 'end' , function streamEnded ( ) { cancellable = false ; } ) ; } } , } ; } ; export const cancellationToken = ( cancellation ? ) => async ( ctx , next ) => { const { config : { method } } = ctx ; if ( ! cancellation ) { return await next ( ) ; } if ( method && ! cancellableMethods . has ( method . toUpperCase ( ) ) ) { cancellation . cancelable = false ; } if ( ! cancellation . cancelable || ! cancellation . source ) { return await next ( ) ; } if ( ! cancellation . source . token . throwIfRequested ) { if ( ! production ) { throw new Error ( 'Missing cancellation function. Are you trying to use HttpClient via workers threads?' ) ; } else { return await next ( ) ; } } const { onRequestFinish , cancelToken } = handleCancellation ( ctx , cancellation ) ; ctx . config . cancelToken = cancelToken ; try { await next ( ) ; } finally { onRequestFinish ( ) ; } } ;