intereq
Version:
Apply interceptors to `fetch` and create a custom request function.
38 lines (32 loc) • 1.75 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.intereq = factory());
}(this, (function () { 'use strict';
/**
* Apply interceptors to `fetch` and create a custom request function.
* @param fetch - Yours environment Fetch function.
* @param interceptors - Interceptors as a kind of protocol to handle requests.
*/
var createRequest = function (fetch, ref) {
if ( ref === void 0 ) ref = {};
var onError = ref.onError; if ( onError === void 0 ) onError = function (reason) { return Promise.reject(reason); };
var onRequest = ref.onRequest; if ( onRequest === void 0 ) onRequest = function (options) { return options; };
var onRequestError = ref.onRequestError; if ( onRequestError === void 0 ) onRequestError = onError;
var onResponse = ref.onResponse; if ( onResponse === void 0 ) onResponse = function (response) { return Promise.resolve(response); };
var onResponseError = ref.onResponseError; if ( onResponseError === void 0 ) onResponseError = onError;
return function () {
// `arguments` instead of `...args` to improve performance and reduce
// bundle size. TS/Babel/Bublé don't need to transpile it.
var params = arguments;
try {
// `.apply(null, args)` instead of `(...args)` for same reason as above.
var options = onRequest.apply(null, params);
return fetch(options.url, options).then(onResponse).catch(onResponseError);
} catch (reason) {
return onRequestError(reason);
}
};
};
return createRequest;
})));