UNPKG

@bitty/create-request

Version:

Apply interceptors in `fetch` to create a custom request functions.

28 lines (26 loc) 1.45 kB
/// <reference lib="dom" /> /** * Apply interceptors to `fetch` and create a custom request function. * @param {Fetch} fetch - Yours environment Fetch function. * @param {RequestInterceptors} [interceptors] - Interceptors as a kind of protocol to handle requests. */ function createRequest(fetch, _a) { var _b = _a === void 0 ? {} : _a, _c = _b.onError, onError = _c === void 0 ? function (reason) { return Promise.reject(reason); } : _c, _d = _b.onRequest, onRequest = _d === void 0 ? function (options) { return options; } : _d, _e = _b.onRequestError, onRequestError = _e === void 0 ? onError : _e, _f = _b.onResponse, onResponse = _f === void 0 ? function (response) { return Promise.resolve(response); } : _f, _g = _b.onResponseError, onResponseError = _g === void 0 ? onError : _g; 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); } }; } export { createRequest as default }; //# sourceMappingURL=index.mjs.map