apollo-link-dedup
Version:
Deduplicates queries that are currently on the wire
73 lines (68 loc) • 3.51 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('tslib'), require('apollo-link')) :
typeof define === 'function' && define.amd ? define(['exports', 'tslib', 'apollo-link'], factory) :
(global = global || self, factory((global.apolloLink = global.apolloLink || {}, global.apolloLink.dedup = {}), global.tslib, global.apolloLink.core));
}(this, (function (exports, tslib_1, apolloLink) { 'use strict';
var DedupLink = (function (_super) {
tslib_1.__extends(DedupLink, _super);
function DedupLink() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.inFlightRequestObservables = new Map();
_this.subscribers = new Map();
return _this;
}
DedupLink.prototype.request = function (operation, forward) {
var _this = this;
if (operation.getContext().forceFetch) {
return forward(operation);
}
var key = operation.toKey();
if (!this.inFlightRequestObservables.get(key)) {
var singleObserver_1 = forward(operation);
var subscription_1;
var sharedObserver = new apolloLink.Observable(function (observer) {
if (!_this.subscribers.has(key))
_this.subscribers.set(key, new Set());
_this.subscribers.get(key).add(observer);
if (!subscription_1) {
subscription_1 = singleObserver_1.subscribe({
next: function (result) {
var subscribers = _this.subscribers.get(key);
_this.subscribers.delete(key);
_this.inFlightRequestObservables.delete(key);
if (subscribers) {
subscribers.forEach(function (obs) { return obs.next(result); });
subscribers.forEach(function (obs) { return obs.complete(); });
}
},
error: function (error) {
var subscribers = _this.subscribers.get(key);
_this.subscribers.delete(key);
_this.inFlightRequestObservables.delete(key);
if (subscribers) {
subscribers.forEach(function (obs) { return obs.error(error); });
}
},
});
}
return function () {
if (_this.subscribers.has(key)) {
_this.subscribers.get(key).delete(observer);
if (_this.subscribers.get(key).size === 0) {
_this.inFlightRequestObservables.delete(key);
if (subscription_1)
subscription_1.unsubscribe();
}
}
};
});
this.inFlightRequestObservables.set(key, sharedObserver);
}
return this.inFlightRequestObservables.get(key);
};
return DedupLink;
}(apolloLink.ApolloLink));
exports.DedupLink = DedupLink;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=bundle.umd.js.map