UNPKG

wretch-middlewares

Version:

Middlewares for the wretch library

70 lines 2.54 kB
/* Defaults */ var defaultSkip = function (_, opts) { return (opts.skipDedupe || opts.method !== 'GET'); }; var defaultKey = function (url, opts) { return opts.method + '@' + url; }; var defaultResolver = function (response) { return response.clone(); }; /** * ## Dedupe middleware * * #### Prevents having multiple identical requests on the fly at the same time. * * **Options** * * - *skip* `(url, opts) => boolean` * * > If skip returns true, then the dedupe check is skipped. * * - *key* `(url, opts) => string` * * > Returns a key that is used to identify the request. * * - *resolver* `(response: Response) => Response` * * > This function is called when resolving the fetch response from duplicate calls. * By default it clones the response to allow reading the body from multiple sources. */ export var dedupe = function (_a) { var _b = _a === void 0 ? {} : _a, _c = _b.skip, skip = _c === void 0 ? defaultSkip : _c, _d = _b.key, key = _d === void 0 ? defaultKey : _d, _e = _b.resolver, resolver = _e === void 0 ? defaultResolver : _e; var inflight = new Map(); return function (next) { return function (url, opts) { if (skip(url, opts)) { return next(url, opts); } var _key = key(url, opts); if (!inflight.has(_key)) { inflight.set(_key, []); } else { return new Promise(function (resolve, reject) { inflight.get(_key).push([resolve, reject]); }); } try { return next(url, opts) .then(function (response) { // Resolve pending promises inflight.get(_key).forEach(function (_a) { var resolve = _a[0]; return resolve(resolver(response)); }); // Remove the inflight pending promises inflight.delete(_key); // Return the original response return response; }) .catch(function (error) { // Reject pending promises on error inflight.get(_key).forEach(function (_a) { var resolve = _a[0], reject = _a[1]; return reject(error); }); inflight.delete(_key); throw error; }); } catch (error) { inflight.delete(_key); return Promise.reject(error); } }; }; }; //# sourceMappingURL=index.js.map