Created
March 1, 2018 18:04
-
-
Save surfjedi/1595edd8ad2cb0175fa8a9ef342358d9 to your computer and use it in GitHub Desktop.
fetch interceptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//NOTE: inspired and modified form https://github.com/werk85/fetch-intercept | |
function attach(env) { | |
// Make sure fetch is available in the given environment | |
if (!env.fetch) { | |
try { | |
console.log('Env has fetch available'); | |
// require('whatwg-fetch'); | |
} catch (err) { | |
throw Error('No fetch available. Unable to register fetch-intercept'); | |
} | |
} | |
env.fetch = (function (fetch) { | |
return function (...args) { | |
return interceptor(fetch, ...args); | |
}; | |
})(env.fetch); | |
} | |
attach(window); | |
let interceptors = []; | |
function interceptor(fetch, ...args) { | |
const reversedInterceptors = interceptors.reduce((array, interceptor) => [interceptor].concat(array), []); | |
let promise = Promise.resolve(args); | |
// Register request interceptors | |
reversedInterceptors.forEach(({ request, requestError }) => { | |
if (request || requestError) { | |
promise = promise.then(args => request(...args), requestError); | |
} | |
}); | |
// Register fetch call | |
promise = promise.then(args => fetch(...args)); | |
// Register response interceptors | |
reversedInterceptors.forEach(({ response, responseError }) => { | |
if (response || responseError) { | |
promise = promise.then(response, responseError); | |
} | |
}); | |
return promise; | |
} | |
module.exports = { | |
register: function (interceptor) { | |
interceptors.push(interceptor); | |
return () => { | |
const index = interceptors.indexOf(interceptor); | |
if (index >= 0) { | |
interceptors.splice(index, 1); | |
} | |
}; | |
}, | |
clear: function () { | |
interceptors = []; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment