1 | (function (global, factory) {
|
2 | if (typeof define === "function" && define.amd) {
|
3 | define(["exports", "tslib", "apollo-utilities", "apollo-link", "symbol-observable", "ts-invariant", "graphql/language/visitor"], factory);
|
4 | } else if (typeof exports !== "undefined") {
|
5 | factory(exports, require("tslib"), require("apollo-utilities"), require("apollo-link"), require("symbol-observable"), require("ts-invariant"), require("graphql/language/visitor"));
|
6 | } else {
|
7 | var mod = {
|
8 | exports: {}
|
9 | };
|
10 | factory(mod.exports, global.tslib, global.apolloUtilities, global.apolloLink, global.symbolObservable, global.tsInvariant, global.visitor);
|
11 | global.unknown = mod.exports;
|
12 | }
|
13 | })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports, _tslib, _apolloUtilities, _apolloLink, _symbolObservable, _tsInvariant, _visitor) {
|
14 |
|
15 | _exports.__esModule = true;
|
16 | _exports.isApolloError = isApolloError;
|
17 | _exports.ObservableQuery = _exports.NetworkStatus = _exports.FetchType = _exports.ApolloError = _exports.ApolloClient = _exports.default = void 0;
|
18 | _symbolObservable = _interopRequireDefault(_symbolObservable);
|
19 |
|
20 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
21 |
|
22 | var NetworkStatus;
|
23 | _exports.NetworkStatus = NetworkStatus;
|
24 |
|
25 | (function (NetworkStatus) {
|
26 | NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
|
27 | NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
|
28 | NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
|
29 | NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
|
30 | NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
|
31 | NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
|
32 | NetworkStatus[NetworkStatus["error"] = 8] = "error";
|
33 | })(NetworkStatus || (_exports.NetworkStatus = NetworkStatus = {}));
|
34 |
|
35 | function isNetworkRequestInFlight(networkStatus) {
|
36 | return networkStatus < 7;
|
37 | }
|
38 |
|
39 | var Observable = function (_super) {
|
40 | (0, _tslib.__extends)(Observable, _super);
|
41 |
|
42 | function Observable() {
|
43 | return _super !== null && _super.apply(this, arguments) || this;
|
44 | }
|
45 |
|
46 | Observable.prototype[_symbolObservable.default] = function () {
|
47 | return this;
|
48 | };
|
49 |
|
50 | Observable.prototype['@@observable'] = function () {
|
51 | return this;
|
52 | };
|
53 |
|
54 | return Observable;
|
55 | }(_apolloLink.Observable);
|
56 |
|
57 | function isNonEmptyArray(value) {
|
58 | return Array.isArray(value) && value.length > 0;
|
59 | }
|
60 |
|
61 | function isApolloError(err) {
|
62 | return err.hasOwnProperty('graphQLErrors');
|
63 | }
|
64 |
|
65 | var generateErrorMessage = function (err) {
|
66 | var message = '';
|
67 |
|
68 | if (isNonEmptyArray(err.graphQLErrors)) {
|
69 | err.graphQLErrors.forEach(function (graphQLError) {
|
70 | var errorMessage = graphQLError ? graphQLError.message : 'Error message not found.';
|
71 | message += "GraphQL error: " + errorMessage + "\n";
|
72 | });
|
73 | }
|
74 |
|
75 | if (err.networkError) {
|
76 | message += 'Network error: ' + err.networkError.message + '\n';
|
77 | }
|
78 |
|
79 | message = message.replace(/\n$/, '');
|
80 | return message;
|
81 | };
|
82 |
|
83 | var ApolloError = function (_super) {
|
84 | (0, _tslib.__extends)(ApolloError, _super);
|
85 |
|
86 | function ApolloError(_a) {
|
87 | var graphQLErrors = _a.graphQLErrors,
|
88 | networkError = _a.networkError,
|
89 | errorMessage = _a.errorMessage,
|
90 | extraInfo = _a.extraInfo;
|
91 |
|
92 | var _this = _super.call(this, errorMessage) || this;
|
93 |
|
94 | _this.graphQLErrors = graphQLErrors || [];
|
95 | _this.networkError = networkError || null;
|
96 |
|
97 | if (!errorMessage) {
|
98 | _this.message = generateErrorMessage(_this);
|
99 | } else {
|
100 | _this.message = errorMessage;
|
101 | }
|
102 |
|
103 | _this.extraInfo = extraInfo;
|
104 | _this.__proto__ = ApolloError.prototype;
|
105 | return _this;
|
106 | }
|
107 |
|
108 | return ApolloError;
|
109 | }(Error);
|
110 |
|
111 | _exports.ApolloError = ApolloError;
|
112 | var FetchType;
|
113 | _exports.FetchType = FetchType;
|
114 |
|
115 | (function (FetchType) {
|
116 | FetchType[FetchType["normal"] = 1] = "normal";
|
117 | FetchType[FetchType["refetch"] = 2] = "refetch";
|
118 | FetchType[FetchType["poll"] = 3] = "poll";
|
119 | })(FetchType || (_exports.FetchType = FetchType = {}));
|
120 |
|
121 | var hasError = function (storeValue, policy) {
|
122 | if (policy === void 0) {
|
123 | policy = 'none';
|
124 | }
|
125 |
|
126 | return storeValue && (storeValue.networkError || policy === 'none' && isNonEmptyArray(storeValue.graphQLErrors));
|
127 | };
|
128 |
|
129 | var ObservableQuery = function (_super) {
|
130 | (0, _tslib.__extends)(ObservableQuery, _super);
|
131 |
|
132 | function ObservableQuery(_a) {
|
133 | var queryManager = _a.queryManager,
|
134 | options = _a.options,
|
135 | _b = _a.shouldSubscribe,
|
136 | shouldSubscribe = _b === void 0 ? true : _b;
|
137 |
|
138 | var _this = _super.call(this, function (observer) {
|
139 | return _this.onSubscribe(observer);
|
140 | }) || this;
|
141 |
|
142 | _this.observers = new Set();
|
143 | _this.subscriptions = new Set();
|
144 | _this.isTornDown = false;
|
145 | _this.options = options;
|
146 | _this.variables = options.variables || {};
|
147 | _this.queryId = queryManager.generateQueryId();
|
148 | _this.shouldSubscribe = shouldSubscribe;
|
149 | var opDef = (0, _apolloUtilities.getOperationDefinition)(options.query);
|
150 | _this.queryName = opDef && opDef.name && opDef.name.value;
|
151 | _this.queryManager = queryManager;
|
152 | return _this;
|
153 | }
|
154 |
|
155 | ObservableQuery.prototype.result = function () {
|
156 | var _this = this;
|
157 |
|
158 | return new Promise(function (resolve, reject) {
|
159 | var observer = {
|
160 | next: function (result) {
|
161 | resolve(result);
|
162 |
|
163 | _this.observers.delete(observer);
|
164 |
|
165 | if (!_this.observers.size) {
|
166 | _this.queryManager.removeQuery(_this.queryId);
|
167 | }
|
168 |
|
169 | setTimeout(function () {
|
170 | subscription.unsubscribe();
|
171 | }, 0);
|
172 | },
|
173 | error: reject
|
174 | };
|
175 |
|
176 | var subscription = _this.subscribe(observer);
|
177 | });
|
178 | };
|
179 |
|
180 | ObservableQuery.prototype.currentResult = function () {
|
181 | var result = this.getCurrentResult();
|
182 |
|
183 | if (result.data === undefined) {
|
184 | result.data = {};
|
185 | }
|
186 |
|
187 | return result;
|
188 | };
|
189 |
|
190 | ObservableQuery.prototype.getCurrentResult = function () {
|
191 | if (this.isTornDown) {
|
192 | var lastResult = this.lastResult;
|
193 | return {
|
194 | data: !this.lastError && lastResult && lastResult.data || void 0,
|
195 | error: this.lastError,
|
196 | loading: false,
|
197 | networkStatus: NetworkStatus.error
|
198 | };
|
199 | }
|
200 |
|
201 | var _a = this.queryManager.getCurrentQueryResult(this),
|
202 | data = _a.data,
|
203 | partial = _a.partial;
|
204 |
|
205 | var queryStoreValue = this.queryManager.queryStore.get(this.queryId);
|
206 | var result;
|
207 | var fetchPolicy = this.options.fetchPolicy;
|
208 | var isNetworkFetchPolicy = fetchPolicy === 'network-only' || fetchPolicy === 'no-cache';
|
209 |
|
210 | if (queryStoreValue) {
|
211 | var networkStatus = queryStoreValue.networkStatus;
|
212 |
|
213 | if (hasError(queryStoreValue, this.options.errorPolicy)) {
|
214 | return {
|
215 | data: void 0,
|
216 | loading: false,
|
217 | networkStatus: networkStatus,
|
218 | error: new ApolloError({
|
219 | graphQLErrors: queryStoreValue.graphQLErrors,
|
220 | networkError: queryStoreValue.networkError
|
221 | })
|
222 | };
|
223 | }
|
224 |
|
225 | if (queryStoreValue.variables) {
|
226 | this.options.variables = (0, _tslib.__assign)((0, _tslib.__assign)({}, this.options.variables), queryStoreValue.variables);
|
227 | this.variables = this.options.variables;
|
228 | }
|
229 |
|
230 | result = {
|
231 | data: data,
|
232 | loading: isNetworkRequestInFlight(networkStatus),
|
233 | networkStatus: networkStatus
|
234 | };
|
235 |
|
236 | if (queryStoreValue.graphQLErrors && this.options.errorPolicy === 'all') {
|
237 | result.errors = queryStoreValue.graphQLErrors;
|
238 | }
|
239 | } else {
|
240 | var loading = isNetworkFetchPolicy || partial && fetchPolicy !== 'cache-only';
|
241 | result = {
|
242 | data: data,
|
243 | loading: loading,
|
244 | networkStatus: loading ? NetworkStatus.loading : NetworkStatus.ready
|
245 | };
|
246 | }
|
247 |
|
248 | if (!partial) {
|
249 | this.updateLastResult((0, _tslib.__assign)((0, _tslib.__assign)({}, result), {
|
250 | stale: false
|
251 | }));
|
252 | }
|
253 |
|
254 | return (0, _tslib.__assign)((0, _tslib.__assign)({}, result), {
|
255 | partial: partial
|
256 | });
|
257 | };
|
258 |
|
259 | ObservableQuery.prototype.isDifferentFromLastResult = function (newResult) {
|
260 | var snapshot = this.lastResultSnapshot;
|
261 | return !(snapshot && newResult && snapshot.networkStatus === newResult.networkStatus && snapshot.stale === newResult.stale && (0, _apolloUtilities.isEqual)(snapshot.data, newResult.data));
|
262 | };
|
263 |
|
264 | ObservableQuery.prototype.getLastResult = function () {
|
265 | return this.lastResult;
|
266 | };
|
267 |
|
268 | ObservableQuery.prototype.getLastError = function () {
|
269 | return this.lastError;
|
270 | };
|
271 |
|
272 | ObservableQuery.prototype.resetLastResults = function () {
|
273 | delete this.lastResult;
|
274 | delete this.lastResultSnapshot;
|
275 | delete this.lastError;
|
276 | this.isTornDown = false;
|
277 | };
|
278 |
|
279 | ObservableQuery.prototype.resetQueryStoreErrors = function () {
|
280 | var queryStore = this.queryManager.queryStore.get(this.queryId);
|
281 |
|
282 | if (queryStore) {
|
283 | queryStore.networkError = null;
|
284 | queryStore.graphQLErrors = [];
|
285 | }
|
286 | };
|
287 |
|
288 | ObservableQuery.prototype.refetch = function (variables) {
|
289 | var fetchPolicy = this.options.fetchPolicy;
|
290 |
|
291 | if (fetchPolicy === 'cache-only') {
|
292 | return Promise.reject(process.env.NODE_ENV === "production" ? new _tsInvariant.InvariantError(1) : new _tsInvariant.InvariantError('cache-only fetchPolicy option should not be used together with query refetch.'));
|
293 | }
|
294 |
|
295 | if (fetchPolicy !== 'no-cache' && fetchPolicy !== 'cache-and-network') {
|
296 | fetchPolicy = 'network-only';
|
297 | }
|
298 |
|
299 | if (!(0, _apolloUtilities.isEqual)(this.variables, variables)) {
|
300 | this.variables = (0, _tslib.__assign)((0, _tslib.__assign)({}, this.variables), variables);
|
301 | }
|
302 |
|
303 | if (!(0, _apolloUtilities.isEqual)(this.options.variables, this.variables)) {
|
304 | this.options.variables = (0, _tslib.__assign)((0, _tslib.__assign)({}, this.options.variables), this.variables);
|
305 | }
|
306 |
|
307 | return this.queryManager.fetchQuery(this.queryId, (0, _tslib.__assign)((0, _tslib.__assign)({}, this.options), {
|
308 | fetchPolicy: fetchPolicy
|
309 | }), FetchType.refetch);
|
310 | };
|
311 |
|
312 | ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
|
313 | var _this = this;
|
314 |
|
315 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(fetchMoreOptions.updateQuery, 2) : (0, _tsInvariant.invariant)(fetchMoreOptions.updateQuery, 'updateQuery option is required. This function defines how to update the query data with the new results.');
|
316 | var combinedOptions = (0, _tslib.__assign)((0, _tslib.__assign)({}, fetchMoreOptions.query ? fetchMoreOptions : (0, _tslib.__assign)((0, _tslib.__assign)((0, _tslib.__assign)({}, this.options), fetchMoreOptions), {
|
317 | variables: (0, _tslib.__assign)((0, _tslib.__assign)({}, this.variables), fetchMoreOptions.variables)
|
318 | })), {
|
319 | fetchPolicy: 'network-only'
|
320 | });
|
321 | var qid = this.queryManager.generateQueryId();
|
322 | return this.queryManager.fetchQuery(qid, combinedOptions, FetchType.normal, this.queryId).then(function (fetchMoreResult) {
|
323 | _this.updateQuery(function (previousResult) {
|
324 | return fetchMoreOptions.updateQuery(previousResult, {
|
325 | fetchMoreResult: fetchMoreResult.data,
|
326 | variables: combinedOptions.variables
|
327 | });
|
328 | });
|
329 |
|
330 | _this.queryManager.stopQuery(qid);
|
331 |
|
332 | return fetchMoreResult;
|
333 | }, function (error) {
|
334 | _this.queryManager.stopQuery(qid);
|
335 |
|
336 | throw error;
|
337 | });
|
338 | };
|
339 |
|
340 | ObservableQuery.prototype.subscribeToMore = function (options) {
|
341 | var _this = this;
|
342 |
|
343 | var subscription = this.queryManager.startGraphQLSubscription({
|
344 | query: options.document,
|
345 | variables: options.variables
|
346 | }).subscribe({
|
347 | next: function (subscriptionData) {
|
348 | var updateQuery = options.updateQuery;
|
349 |
|
350 | if (updateQuery) {
|
351 | _this.updateQuery(function (previous, _a) {
|
352 | var variables = _a.variables;
|
353 | return updateQuery(previous, {
|
354 | subscriptionData: subscriptionData,
|
355 | variables: variables
|
356 | });
|
357 | });
|
358 | }
|
359 | },
|
360 | error: function (err) {
|
361 | if (options.onError) {
|
362 | options.onError(err);
|
363 | return;
|
364 | }
|
365 |
|
366 | process.env.NODE_ENV === "production" || _tsInvariant.invariant.error('Unhandled GraphQL subscription error', err);
|
367 | }
|
368 | });
|
369 | this.subscriptions.add(subscription);
|
370 | return function () {
|
371 | if (_this.subscriptions.delete(subscription)) {
|
372 | subscription.unsubscribe();
|
373 | }
|
374 | };
|
375 | };
|
376 |
|
377 | ObservableQuery.prototype.setOptions = function (opts) {
|
378 | var oldFetchPolicy = this.options.fetchPolicy;
|
379 | this.options = (0, _tslib.__assign)((0, _tslib.__assign)({}, this.options), opts);
|
380 |
|
381 | if (opts.pollInterval) {
|
382 | this.startPolling(opts.pollInterval);
|
383 | } else if (opts.pollInterval === 0) {
|
384 | this.stopPolling();
|
385 | }
|
386 |
|
387 | var fetchPolicy = opts.fetchPolicy;
|
388 | return this.setVariables(this.options.variables, oldFetchPolicy !== fetchPolicy && (oldFetchPolicy === 'cache-only' || oldFetchPolicy === 'standby' || fetchPolicy === 'network-only'), opts.fetchResults);
|
389 | };
|
390 |
|
391 | ObservableQuery.prototype.setVariables = function (variables, tryFetch, fetchResults) {
|
392 | if (tryFetch === void 0) {
|
393 | tryFetch = false;
|
394 | }
|
395 |
|
396 | if (fetchResults === void 0) {
|
397 | fetchResults = true;
|
398 | }
|
399 |
|
400 | this.isTornDown = false;
|
401 | variables = variables || this.variables;
|
402 |
|
403 | if (!tryFetch && (0, _apolloUtilities.isEqual)(variables, this.variables)) {
|
404 | return this.observers.size && fetchResults ? this.result() : Promise.resolve();
|
405 | }
|
406 |
|
407 | this.variables = this.options.variables = variables;
|
408 |
|
409 | if (!this.observers.size) {
|
410 | return Promise.resolve();
|
411 | }
|
412 |
|
413 | return this.queryManager.fetchQuery(this.queryId, this.options);
|
414 | };
|
415 |
|
416 | ObservableQuery.prototype.updateQuery = function (mapFn) {
|
417 | var queryManager = this.queryManager;
|
418 |
|
419 | var _a = queryManager.getQueryWithPreviousResult(this.queryId),
|
420 | previousResult = _a.previousResult,
|
421 | variables = _a.variables,
|
422 | document = _a.document;
|
423 |
|
424 | var newResult = (0, _apolloUtilities.tryFunctionOrLogError)(function () {
|
425 | return mapFn(previousResult, {
|
426 | variables: variables
|
427 | });
|
428 | });
|
429 |
|
430 | if (newResult) {
|
431 | queryManager.dataStore.markUpdateQueryResult(document, variables, newResult);
|
432 | queryManager.broadcastQueries();
|
433 | }
|
434 | };
|
435 |
|
436 | ObservableQuery.prototype.stopPolling = function () {
|
437 | this.queryManager.stopPollingQuery(this.queryId);
|
438 | this.options.pollInterval = undefined;
|
439 | };
|
440 |
|
441 | ObservableQuery.prototype.startPolling = function (pollInterval) {
|
442 | assertNotCacheFirstOrOnly(this);
|
443 | this.options.pollInterval = pollInterval;
|
444 | this.queryManager.startPollingQuery(this.options, this.queryId);
|
445 | };
|
446 |
|
447 | ObservableQuery.prototype.updateLastResult = function (newResult) {
|
448 | var previousResult = this.lastResult;
|
449 | this.lastResult = newResult;
|
450 | this.lastResultSnapshot = this.queryManager.assumeImmutableResults ? newResult : (0, _apolloUtilities.cloneDeep)(newResult);
|
451 | return previousResult;
|
452 | };
|
453 |
|
454 | ObservableQuery.prototype.onSubscribe = function (observer) {
|
455 | var _this = this;
|
456 |
|
457 | try {
|
458 | var subObserver = observer._subscription._observer;
|
459 |
|
460 | if (subObserver && !subObserver.error) {
|
461 | subObserver.error = defaultSubscriptionObserverErrorCallback;
|
462 | }
|
463 | } catch (_a) {}
|
464 |
|
465 | var first = !this.observers.size;
|
466 | this.observers.add(observer);
|
467 | if (observer.next && this.lastResult) observer.next(this.lastResult);
|
468 | if (observer.error && this.lastError) observer.error(this.lastError);
|
469 |
|
470 | if (first) {
|
471 | this.setUpQuery();
|
472 | }
|
473 |
|
474 | return function () {
|
475 | if (_this.observers.delete(observer) && !_this.observers.size) {
|
476 | _this.tearDownQuery();
|
477 | }
|
478 | };
|
479 | };
|
480 |
|
481 | ObservableQuery.prototype.setUpQuery = function () {
|
482 | var _this = this;
|
483 |
|
484 | var _a = this,
|
485 | queryManager = _a.queryManager,
|
486 | queryId = _a.queryId;
|
487 |
|
488 | if (this.shouldSubscribe) {
|
489 | queryManager.addObservableQuery(queryId, this);
|
490 | }
|
491 |
|
492 | if (this.options.pollInterval) {
|
493 | assertNotCacheFirstOrOnly(this);
|
494 | queryManager.startPollingQuery(this.options, queryId);
|
495 | }
|
496 |
|
497 | var onError = function (error) {
|
498 | _this.updateLastResult((0, _tslib.__assign)((0, _tslib.__assign)({}, _this.lastResult), {
|
499 | errors: error.graphQLErrors,
|
500 | networkStatus: NetworkStatus.error,
|
501 | loading: false
|
502 | }));
|
503 |
|
504 | iterateObserversSafely(_this.observers, 'error', _this.lastError = error);
|
505 | };
|
506 |
|
507 | queryManager.observeQuery(queryId, this.options, {
|
508 | next: function (result) {
|
509 | if (_this.lastError || _this.isDifferentFromLastResult(result)) {
|
510 | var previousResult_1 = _this.updateLastResult(result);
|
511 |
|
512 | var _a = _this.options,
|
513 | query_1 = _a.query,
|
514 | variables = _a.variables,
|
515 | fetchPolicy_1 = _a.fetchPolicy;
|
516 |
|
517 | if (queryManager.transform(query_1).hasClientExports) {
|
518 | queryManager.getLocalState().addExportedVariables(query_1, variables).then(function (variables) {
|
519 | var previousVariables = _this.variables;
|
520 | _this.variables = _this.options.variables = variables;
|
521 |
|
522 | if (!result.loading && previousResult_1 && fetchPolicy_1 !== 'cache-only' && queryManager.transform(query_1).serverQuery && !(0, _apolloUtilities.isEqual)(previousVariables, variables)) {
|
523 | _this.refetch();
|
524 | } else {
|
525 | iterateObserversSafely(_this.observers, 'next', result);
|
526 | }
|
527 | });
|
528 | } else {
|
529 | iterateObserversSafely(_this.observers, 'next', result);
|
530 | }
|
531 | }
|
532 | },
|
533 | error: onError
|
534 | }).catch(onError);
|
535 | };
|
536 |
|
537 | ObservableQuery.prototype.tearDownQuery = function () {
|
538 | var queryManager = this.queryManager;
|
539 | this.isTornDown = true;
|
540 | queryManager.stopPollingQuery(this.queryId);
|
541 | this.subscriptions.forEach(function (sub) {
|
542 | return sub.unsubscribe();
|
543 | });
|
544 | this.subscriptions.clear();
|
545 | queryManager.removeObservableQuery(this.queryId);
|
546 | queryManager.stopQuery(this.queryId);
|
547 | this.observers.clear();
|
548 | };
|
549 |
|
550 | return ObservableQuery;
|
551 | }(Observable);
|
552 |
|
553 | _exports.ObservableQuery = ObservableQuery;
|
554 |
|
555 | function defaultSubscriptionObserverErrorCallback(error) {
|
556 | process.env.NODE_ENV === "production" || _tsInvariant.invariant.error('Unhandled error', error.message, error.stack);
|
557 | }
|
558 |
|
559 | function iterateObserversSafely(observers, method, argument) {
|
560 | var observersWithMethod = [];
|
561 | observers.forEach(function (obs) {
|
562 | return obs[method] && observersWithMethod.push(obs);
|
563 | });
|
564 | observersWithMethod.forEach(function (obs) {
|
565 | return obs[method](argument);
|
566 | });
|
567 | }
|
568 |
|
569 | function assertNotCacheFirstOrOnly(obsQuery) {
|
570 | var fetchPolicy = obsQuery.options.fetchPolicy;
|
571 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(fetchPolicy !== 'cache-first' && fetchPolicy !== 'cache-only', 3) : (0, _tsInvariant.invariant)(fetchPolicy !== 'cache-first' && fetchPolicy !== 'cache-only', 'Queries that specify the cache-first and cache-only fetchPolicies cannot also be polling queries.');
|
572 | }
|
573 |
|
574 | var MutationStore = function () {
|
575 | function MutationStore() {
|
576 | this.store = {};
|
577 | }
|
578 |
|
579 | MutationStore.prototype.getStore = function () {
|
580 | return this.store;
|
581 | };
|
582 |
|
583 | MutationStore.prototype.get = function (mutationId) {
|
584 | return this.store[mutationId];
|
585 | };
|
586 |
|
587 | MutationStore.prototype.initMutation = function (mutationId, mutation, variables) {
|
588 | this.store[mutationId] = {
|
589 | mutation: mutation,
|
590 | variables: variables || {},
|
591 | loading: true,
|
592 | error: null
|
593 | };
|
594 | };
|
595 |
|
596 | MutationStore.prototype.markMutationError = function (mutationId, error) {
|
597 | var mutation = this.store[mutationId];
|
598 |
|
599 | if (mutation) {
|
600 | mutation.loading = false;
|
601 | mutation.error = error;
|
602 | }
|
603 | };
|
604 |
|
605 | MutationStore.prototype.markMutationResult = function (mutationId) {
|
606 | var mutation = this.store[mutationId];
|
607 |
|
608 | if (mutation) {
|
609 | mutation.loading = false;
|
610 | mutation.error = null;
|
611 | }
|
612 | };
|
613 |
|
614 | MutationStore.prototype.reset = function () {
|
615 | this.store = {};
|
616 | };
|
617 |
|
618 | return MutationStore;
|
619 | }();
|
620 |
|
621 | var QueryStore = function () {
|
622 | function QueryStore() {
|
623 | this.store = {};
|
624 | }
|
625 |
|
626 | QueryStore.prototype.getStore = function () {
|
627 | return this.store;
|
628 | };
|
629 |
|
630 | QueryStore.prototype.get = function (queryId) {
|
631 | return this.store[queryId];
|
632 | };
|
633 |
|
634 | QueryStore.prototype.initQuery = function (query) {
|
635 | var previousQuery = this.store[query.queryId];
|
636 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(!previousQuery || previousQuery.document === query.document || (0, _apolloUtilities.isEqual)(previousQuery.document, query.document), 19) : (0, _tsInvariant.invariant)(!previousQuery || previousQuery.document === query.document || (0, _apolloUtilities.isEqual)(previousQuery.document, query.document), 'Internal Error: may not update existing query string in store');
|
637 | var isSetVariables = false;
|
638 | var previousVariables = null;
|
639 |
|
640 | if (query.storePreviousVariables && previousQuery && previousQuery.networkStatus !== NetworkStatus.loading) {
|
641 | if (!(0, _apolloUtilities.isEqual)(previousQuery.variables, query.variables)) {
|
642 | isSetVariables = true;
|
643 | previousVariables = previousQuery.variables;
|
644 | }
|
645 | }
|
646 |
|
647 | var networkStatus;
|
648 |
|
649 | if (isSetVariables) {
|
650 | networkStatus = NetworkStatus.setVariables;
|
651 | } else if (query.isPoll) {
|
652 | networkStatus = NetworkStatus.poll;
|
653 | } else if (query.isRefetch) {
|
654 | networkStatus = NetworkStatus.refetch;
|
655 | } else {
|
656 | networkStatus = NetworkStatus.loading;
|
657 | }
|
658 |
|
659 | var graphQLErrors = [];
|
660 |
|
661 | if (previousQuery && previousQuery.graphQLErrors) {
|
662 | graphQLErrors = previousQuery.graphQLErrors;
|
663 | }
|
664 |
|
665 | this.store[query.queryId] = {
|
666 | document: query.document,
|
667 | variables: query.variables,
|
668 | previousVariables: previousVariables,
|
669 | networkError: null,
|
670 | graphQLErrors: graphQLErrors,
|
671 | networkStatus: networkStatus,
|
672 | metadata: query.metadata
|
673 | };
|
674 |
|
675 | if (typeof query.fetchMoreForQueryId === 'string' && this.store[query.fetchMoreForQueryId]) {
|
676 | this.store[query.fetchMoreForQueryId].networkStatus = NetworkStatus.fetchMore;
|
677 | }
|
678 | };
|
679 |
|
680 | QueryStore.prototype.markQueryResult = function (queryId, result, fetchMoreForQueryId) {
|
681 | if (!this.store || !this.store[queryId]) return;
|
682 | this.store[queryId].networkError = null;
|
683 | this.store[queryId].graphQLErrors = isNonEmptyArray(result.errors) ? result.errors : [];
|
684 | this.store[queryId].previousVariables = null;
|
685 | this.store[queryId].networkStatus = NetworkStatus.ready;
|
686 |
|
687 | if (typeof fetchMoreForQueryId === 'string' && this.store[fetchMoreForQueryId]) {
|
688 | this.store[fetchMoreForQueryId].networkStatus = NetworkStatus.ready;
|
689 | }
|
690 | };
|
691 |
|
692 | QueryStore.prototype.markQueryError = function (queryId, error, fetchMoreForQueryId) {
|
693 | if (!this.store || !this.store[queryId]) return;
|
694 | this.store[queryId].networkError = error;
|
695 | this.store[queryId].networkStatus = NetworkStatus.error;
|
696 |
|
697 | if (typeof fetchMoreForQueryId === 'string') {
|
698 | this.markQueryResultClient(fetchMoreForQueryId, true);
|
699 | }
|
700 | };
|
701 |
|
702 | QueryStore.prototype.markQueryResultClient = function (queryId, complete) {
|
703 | var storeValue = this.store && this.store[queryId];
|
704 |
|
705 | if (storeValue) {
|
706 | storeValue.networkError = null;
|
707 | storeValue.previousVariables = null;
|
708 |
|
709 | if (complete) {
|
710 | storeValue.networkStatus = NetworkStatus.ready;
|
711 | }
|
712 | }
|
713 | };
|
714 |
|
715 | QueryStore.prototype.stopQuery = function (queryId) {
|
716 | delete this.store[queryId];
|
717 | };
|
718 |
|
719 | QueryStore.prototype.reset = function (observableQueryIds) {
|
720 | var _this = this;
|
721 |
|
722 | Object.keys(this.store).forEach(function (queryId) {
|
723 | if (observableQueryIds.indexOf(queryId) < 0) {
|
724 | _this.stopQuery(queryId);
|
725 | } else {
|
726 | _this.store[queryId].networkStatus = NetworkStatus.loading;
|
727 | }
|
728 | });
|
729 | };
|
730 |
|
731 | return QueryStore;
|
732 | }();
|
733 |
|
734 | function capitalizeFirstLetter(str) {
|
735 | return str.charAt(0).toUpperCase() + str.slice(1);
|
736 | }
|
737 |
|
738 | var LocalState = function () {
|
739 | function LocalState(_a) {
|
740 | var cache = _a.cache,
|
741 | client = _a.client,
|
742 | resolvers = _a.resolvers,
|
743 | fragmentMatcher = _a.fragmentMatcher;
|
744 | this.cache = cache;
|
745 |
|
746 | if (client) {
|
747 | this.client = client;
|
748 | }
|
749 |
|
750 | if (resolvers) {
|
751 | this.addResolvers(resolvers);
|
752 | }
|
753 |
|
754 | if (fragmentMatcher) {
|
755 | this.setFragmentMatcher(fragmentMatcher);
|
756 | }
|
757 | }
|
758 |
|
759 | LocalState.prototype.addResolvers = function (resolvers) {
|
760 | var _this = this;
|
761 |
|
762 | this.resolvers = this.resolvers || {};
|
763 |
|
764 | if (Array.isArray(resolvers)) {
|
765 | resolvers.forEach(function (resolverGroup) {
|
766 | _this.resolvers = (0, _apolloUtilities.mergeDeep)(_this.resolvers, resolverGroup);
|
767 | });
|
768 | } else {
|
769 | this.resolvers = (0, _apolloUtilities.mergeDeep)(this.resolvers, resolvers);
|
770 | }
|
771 | };
|
772 |
|
773 | LocalState.prototype.setResolvers = function (resolvers) {
|
774 | this.resolvers = {};
|
775 | this.addResolvers(resolvers);
|
776 | };
|
777 |
|
778 | LocalState.prototype.getResolvers = function () {
|
779 | return this.resolvers || {};
|
780 | };
|
781 |
|
782 | LocalState.prototype.runResolvers = function (_a) {
|
783 | var document = _a.document,
|
784 | remoteResult = _a.remoteResult,
|
785 | context = _a.context,
|
786 | variables = _a.variables,
|
787 | _b = _a.onlyRunForcedResolvers,
|
788 | onlyRunForcedResolvers = _b === void 0 ? false : _b;
|
789 | return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
|
790 | return (0, _tslib.__generator)(this, function (_c) {
|
791 | if (document) {
|
792 | return [2, this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) {
|
793 | return (0, _tslib.__assign)((0, _tslib.__assign)({}, remoteResult), {
|
794 | data: localResult.result
|
795 | });
|
796 | })];
|
797 | }
|
798 |
|
799 | return [2, remoteResult];
|
800 | });
|
801 | });
|
802 | };
|
803 |
|
804 | LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {
|
805 | this.fragmentMatcher = fragmentMatcher;
|
806 | };
|
807 |
|
808 | LocalState.prototype.getFragmentMatcher = function () {
|
809 | return this.fragmentMatcher;
|
810 | };
|
811 |
|
812 | LocalState.prototype.clientQuery = function (document) {
|
813 | if ((0, _apolloUtilities.hasDirectives)(['client'], document)) {
|
814 | if (this.resolvers) {
|
815 | return document;
|
816 | }
|
817 |
|
818 | process.env.NODE_ENV === "production" || _tsInvariant.invariant.warn('Found @client directives in a query but no ApolloClient resolvers ' + 'were specified. This means ApolloClient local resolver handling ' + 'has been disabled, and @client directives will be passed through ' + 'to your link chain.');
|
819 | }
|
820 |
|
821 | return null;
|
822 | };
|
823 |
|
824 | LocalState.prototype.serverQuery = function (document) {
|
825 | return this.resolvers ? (0, _apolloUtilities.removeClientSetsFromDocument)(document) : document;
|
826 | };
|
827 |
|
828 | LocalState.prototype.prepareContext = function (context) {
|
829 | if (context === void 0) {
|
830 | context = {};
|
831 | }
|
832 |
|
833 | var cache = this.cache;
|
834 | var newContext = (0, _tslib.__assign)((0, _tslib.__assign)({}, context), {
|
835 | cache: cache,
|
836 | getCacheKey: function (obj) {
|
837 | if (cache.config) {
|
838 | return cache.config.dataIdFromObject(obj);
|
839 | } else {
|
840 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(false, 6) : (0, _tsInvariant.invariant)(false, 'To use context.getCacheKey, you need to use a cache that has ' + 'a configurable dataIdFromObject, like apollo-cache-inmemory.');
|
841 | }
|
842 | }
|
843 | });
|
844 | return newContext;
|
845 | };
|
846 |
|
847 | LocalState.prototype.addExportedVariables = function (document, variables, context) {
|
848 | if (variables === void 0) {
|
849 | variables = {};
|
850 | }
|
851 |
|
852 | if (context === void 0) {
|
853 | context = {};
|
854 | }
|
855 |
|
856 | return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
|
857 | return (0, _tslib.__generator)(this, function (_a) {
|
858 | if (document) {
|
859 | return [2, this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) {
|
860 | return (0, _tslib.__assign)((0, _tslib.__assign)({}, variables), data.exportedVariables);
|
861 | })];
|
862 | }
|
863 |
|
864 | return [2, (0, _tslib.__assign)({}, variables)];
|
865 | });
|
866 | });
|
867 | };
|
868 |
|
869 | LocalState.prototype.shouldForceResolvers = function (document) {
|
870 | var forceResolvers = false;
|
871 | (0, _visitor.visit)(document, {
|
872 | Directive: {
|
873 | enter: function (node) {
|
874 | if (node.name.value === 'client' && node.arguments) {
|
875 | forceResolvers = node.arguments.some(function (arg) {
|
876 | return arg.name.value === 'always' && arg.value.kind === 'BooleanValue' && arg.value.value === true;
|
877 | });
|
878 |
|
879 | if (forceResolvers) {
|
880 | return _visitor.BREAK;
|
881 | }
|
882 | }
|
883 | }
|
884 | }
|
885 | });
|
886 | return forceResolvers;
|
887 | };
|
888 |
|
889 | LocalState.prototype.buildRootValueFromCache = function (document, variables) {
|
890 | return this.cache.diff({
|
891 | query: (0, _apolloUtilities.buildQueryFromSelectionSet)(document),
|
892 | variables: variables,
|
893 | returnPartialData: true,
|
894 | optimistic: false
|
895 | }).result;
|
896 | };
|
897 |
|
898 | LocalState.prototype.resolveDocument = function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {
|
899 | if (context === void 0) {
|
900 | context = {};
|
901 | }
|
902 |
|
903 | if (variables === void 0) {
|
904 | variables = {};
|
905 | }
|
906 |
|
907 | if (fragmentMatcher === void 0) {
|
908 | fragmentMatcher = function () {
|
909 | return true;
|
910 | };
|
911 | }
|
912 |
|
913 | if (onlyRunForcedResolvers === void 0) {
|
914 | onlyRunForcedResolvers = false;
|
915 | }
|
916 |
|
917 | return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
|
918 | var mainDefinition, fragments, fragmentMap, definitionOperation, defaultOperationType, _a, cache, client, execContext;
|
919 |
|
920 | return (0, _tslib.__generator)(this, function (_b) {
|
921 | mainDefinition = (0, _apolloUtilities.getMainDefinition)(document);
|
922 | fragments = (0, _apolloUtilities.getFragmentDefinitions)(document);
|
923 | fragmentMap = (0, _apolloUtilities.createFragmentMap)(fragments);
|
924 | definitionOperation = mainDefinition.operation;
|
925 | defaultOperationType = definitionOperation ? capitalizeFirstLetter(definitionOperation) : 'Query';
|
926 | _a = this, cache = _a.cache, client = _a.client;
|
927 | execContext = {
|
928 | fragmentMap: fragmentMap,
|
929 | context: (0, _tslib.__assign)((0, _tslib.__assign)({}, context), {
|
930 | cache: cache,
|
931 | client: client
|
932 | }),
|
933 | variables: variables,
|
934 | fragmentMatcher: fragmentMatcher,
|
935 | defaultOperationType: defaultOperationType,
|
936 | exportedVariables: {},
|
937 | onlyRunForcedResolvers: onlyRunForcedResolvers
|
938 | };
|
939 | return [2, this.resolveSelectionSet(mainDefinition.selectionSet, rootValue, execContext).then(function (result) {
|
940 | return {
|
941 | result: result,
|
942 | exportedVariables: execContext.exportedVariables
|
943 | };
|
944 | })];
|
945 | });
|
946 | });
|
947 | };
|
948 |
|
949 | LocalState.prototype.resolveSelectionSet = function (selectionSet, rootValue, execContext) {
|
950 | return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
|
951 | var fragmentMap, context, variables, resultsToMerge, execute;
|
952 |
|
953 | var _this = this;
|
954 |
|
955 | return (0, _tslib.__generator)(this, function (_a) {
|
956 | fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;
|
957 | resultsToMerge = [rootValue];
|
958 |
|
959 | execute = function (selection) {
|
960 | return (0, _tslib.__awaiter)(_this, void 0, void 0, function () {
|
961 | var fragment, typeCondition;
|
962 | return (0, _tslib.__generator)(this, function (_a) {
|
963 | if (!(0, _apolloUtilities.shouldInclude)(selection, variables)) {
|
964 | return [2];
|
965 | }
|
966 |
|
967 | if ((0, _apolloUtilities.isField)(selection)) {
|
968 | return [2, this.resolveField(selection, rootValue, execContext).then(function (fieldResult) {
|
969 | var _a;
|
970 |
|
971 | if (typeof fieldResult !== 'undefined') {
|
972 | resultsToMerge.push((_a = {}, _a[(0, _apolloUtilities.resultKeyNameFromField)(selection)] = fieldResult, _a));
|
973 | }
|
974 | })];
|
975 | }
|
976 |
|
977 | if ((0, _apolloUtilities.isInlineFragment)(selection)) {
|
978 | fragment = selection;
|
979 | } else {
|
980 | fragment = fragmentMap[selection.name.value];
|
981 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(fragment, 7) : (0, _tsInvariant.invariant)(fragment, "No fragment named " + selection.name.value);
|
982 | }
|
983 |
|
984 | if (fragment && fragment.typeCondition) {
|
985 | typeCondition = fragment.typeCondition.name.value;
|
986 |
|
987 | if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {
|
988 | return [2, this.resolveSelectionSet(fragment.selectionSet, rootValue, execContext).then(function (fragmentResult) {
|
989 | resultsToMerge.push(fragmentResult);
|
990 | })];
|
991 | }
|
992 | }
|
993 |
|
994 | return [2];
|
995 | });
|
996 | });
|
997 | };
|
998 |
|
999 | return [2, Promise.all(selectionSet.selections.map(execute)).then(function () {
|
1000 | return (0, _apolloUtilities.mergeDeepArray)(resultsToMerge);
|
1001 | })];
|
1002 | });
|
1003 | });
|
1004 | };
|
1005 |
|
1006 | LocalState.prototype.resolveField = function (field, rootValue, execContext) {
|
1007 | return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
|
1008 | var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;
|
1009 |
|
1010 | var _this = this;
|
1011 |
|
1012 | return (0, _tslib.__generator)(this, function (_a) {
|
1013 | variables = execContext.variables;
|
1014 | fieldName = field.name.value;
|
1015 | aliasedFieldName = (0, _apolloUtilities.resultKeyNameFromField)(field);
|
1016 | aliasUsed = fieldName !== aliasedFieldName;
|
1017 | defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];
|
1018 | resultPromise = Promise.resolve(defaultResult);
|
1019 |
|
1020 | if (!execContext.onlyRunForcedResolvers || this.shouldForceResolvers(field)) {
|
1021 | resolverType = rootValue.__typename || execContext.defaultOperationType;
|
1022 | resolverMap = this.resolvers && this.resolvers[resolverType];
|
1023 |
|
1024 | if (resolverMap) {
|
1025 | resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];
|
1026 |
|
1027 | if (resolve) {
|
1028 | resultPromise = Promise.resolve(resolve(rootValue, (0, _apolloUtilities.argumentsObjectFromField)(field, variables), execContext.context, {
|
1029 | field: field,
|
1030 | fragmentMap: execContext.fragmentMap
|
1031 | }));
|
1032 | }
|
1033 | }
|
1034 | }
|
1035 |
|
1036 | return [2, resultPromise.then(function (result) {
|
1037 | if (result === void 0) {
|
1038 | result = defaultResult;
|
1039 | }
|
1040 |
|
1041 | if (field.directives) {
|
1042 | field.directives.forEach(function (directive) {
|
1043 | if (directive.name.value === 'export' && directive.arguments) {
|
1044 | directive.arguments.forEach(function (arg) {
|
1045 | if (arg.name.value === 'as' && arg.value.kind === 'StringValue') {
|
1046 | execContext.exportedVariables[arg.value.value] = result;
|
1047 | }
|
1048 | });
|
1049 | }
|
1050 | });
|
1051 | }
|
1052 |
|
1053 | if (!field.selectionSet) {
|
1054 | return result;
|
1055 | }
|
1056 |
|
1057 | if (result == null) {
|
1058 | return result;
|
1059 | }
|
1060 |
|
1061 | if (Array.isArray(result)) {
|
1062 | return _this.resolveSubSelectedArray(field, result, execContext);
|
1063 | }
|
1064 |
|
1065 | if (field.selectionSet) {
|
1066 | return _this.resolveSelectionSet(field.selectionSet, result, execContext);
|
1067 | }
|
1068 | })];
|
1069 | });
|
1070 | });
|
1071 | };
|
1072 |
|
1073 | LocalState.prototype.resolveSubSelectedArray = function (field, result, execContext) {
|
1074 | var _this = this;
|
1075 |
|
1076 | return Promise.all(result.map(function (item) {
|
1077 | if (item === null) {
|
1078 | return null;
|
1079 | }
|
1080 |
|
1081 | if (Array.isArray(item)) {
|
1082 | return _this.resolveSubSelectedArray(field, item, execContext);
|
1083 | }
|
1084 |
|
1085 | if (field.selectionSet) {
|
1086 | return _this.resolveSelectionSet(field.selectionSet, item, execContext);
|
1087 | }
|
1088 | }));
|
1089 | };
|
1090 |
|
1091 | return LocalState;
|
1092 | }();
|
1093 |
|
1094 | function multiplex(inner) {
|
1095 | var observers = new Set();
|
1096 | var sub = null;
|
1097 | return new Observable(function (observer) {
|
1098 | observers.add(observer);
|
1099 | sub = sub || inner.subscribe({
|
1100 | next: function (value) {
|
1101 | observers.forEach(function (obs) {
|
1102 | return obs.next && obs.next(value);
|
1103 | });
|
1104 | },
|
1105 | error: function (error) {
|
1106 | observers.forEach(function (obs) {
|
1107 | return obs.error && obs.error(error);
|
1108 | });
|
1109 | },
|
1110 | complete: function () {
|
1111 | observers.forEach(function (obs) {
|
1112 | return obs.complete && obs.complete();
|
1113 | });
|
1114 | }
|
1115 | });
|
1116 | return function () {
|
1117 | if (observers.delete(observer) && !observers.size && sub) {
|
1118 | sub.unsubscribe();
|
1119 | sub = null;
|
1120 | }
|
1121 | };
|
1122 | });
|
1123 | }
|
1124 |
|
1125 | function asyncMap(observable, mapFn) {
|
1126 | return new Observable(function (observer) {
|
1127 | var next = observer.next,
|
1128 | error = observer.error,
|
1129 | complete = observer.complete;
|
1130 | var activeNextCount = 0;
|
1131 | var completed = false;
|
1132 | var handler = {
|
1133 | next: function (value) {
|
1134 | ++activeNextCount;
|
1135 | new Promise(function (resolve) {
|
1136 | resolve(mapFn(value));
|
1137 | }).then(function (result) {
|
1138 | --activeNextCount;
|
1139 | next && next.call(observer, result);
|
1140 | completed && handler.complete();
|
1141 | }, function (e) {
|
1142 | --activeNextCount;
|
1143 | error && error.call(observer, e);
|
1144 | });
|
1145 | },
|
1146 | error: function (e) {
|
1147 | error && error.call(observer, e);
|
1148 | },
|
1149 | complete: function () {
|
1150 | completed = true;
|
1151 |
|
1152 | if (!activeNextCount) {
|
1153 | complete && complete.call(observer);
|
1154 | }
|
1155 | }
|
1156 | };
|
1157 | var sub = observable.subscribe(handler);
|
1158 | return function () {
|
1159 | return sub.unsubscribe();
|
1160 | };
|
1161 | });
|
1162 | }
|
1163 |
|
1164 | var hasOwnProperty = Object.prototype.hasOwnProperty;
|
1165 |
|
1166 | var QueryManager = function () {
|
1167 | function QueryManager(_a) {
|
1168 | var link = _a.link,
|
1169 | _b = _a.queryDeduplication,
|
1170 | queryDeduplication = _b === void 0 ? false : _b,
|
1171 | store = _a.store,
|
1172 | _c = _a.onBroadcast,
|
1173 | onBroadcast = _c === void 0 ? function () {
|
1174 | return undefined;
|
1175 | } : _c,
|
1176 | _d = _a.ssrMode,
|
1177 | ssrMode = _d === void 0 ? false : _d,
|
1178 | _e = _a.clientAwareness,
|
1179 | clientAwareness = _e === void 0 ? {} : _e,
|
1180 | localState = _a.localState,
|
1181 | assumeImmutableResults = _a.assumeImmutableResults;
|
1182 | this.mutationStore = new MutationStore();
|
1183 | this.queryStore = new QueryStore();
|
1184 | this.clientAwareness = {};
|
1185 | this.idCounter = 1;
|
1186 | this.queries = new Map();
|
1187 | this.fetchQueryRejectFns = new Map();
|
1188 | this.transformCache = new (_apolloUtilities.canUseWeakMap ? WeakMap : Map)();
|
1189 | this.inFlightLinkObservables = new Map();
|
1190 | this.pollingInfoByQueryId = new Map();
|
1191 | this.link = link;
|
1192 | this.queryDeduplication = queryDeduplication;
|
1193 | this.dataStore = store;
|
1194 | this.onBroadcast = onBroadcast;
|
1195 | this.clientAwareness = clientAwareness;
|
1196 | this.localState = localState || new LocalState({
|
1197 | cache: store.getCache()
|
1198 | });
|
1199 | this.ssrMode = ssrMode;
|
1200 | this.assumeImmutableResults = !!assumeImmutableResults;
|
1201 | }
|
1202 |
|
1203 | QueryManager.prototype.stop = function () {
|
1204 | var _this = this;
|
1205 |
|
1206 | this.queries.forEach(function (_info, queryId) {
|
1207 | _this.stopQueryNoBroadcast(queryId);
|
1208 | });
|
1209 | this.fetchQueryRejectFns.forEach(function (reject) {
|
1210 | reject(process.env.NODE_ENV === "production" ? new _tsInvariant.InvariantError(8) : new _tsInvariant.InvariantError('QueryManager stopped while query was in flight'));
|
1211 | });
|
1212 | };
|
1213 |
|
1214 | QueryManager.prototype.mutate = function (_a) {
|
1215 | var mutation = _a.mutation,
|
1216 | variables = _a.variables,
|
1217 | optimisticResponse = _a.optimisticResponse,
|
1218 | updateQueriesByName = _a.updateQueries,
|
1219 | _b = _a.refetchQueries,
|
1220 | refetchQueries = _b === void 0 ? [] : _b,
|
1221 | _c = _a.awaitRefetchQueries,
|
1222 | awaitRefetchQueries = _c === void 0 ? false : _c,
|
1223 | updateWithProxyFn = _a.update,
|
1224 | _d = _a.errorPolicy,
|
1225 | errorPolicy = _d === void 0 ? 'none' : _d,
|
1226 | fetchPolicy = _a.fetchPolicy,
|
1227 | _e = _a.context,
|
1228 | context = _e === void 0 ? {} : _e;
|
1229 | return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
|
1230 | var mutationId, generateUpdateQueriesInfo, self;
|
1231 |
|
1232 | var _this = this;
|
1233 |
|
1234 | return (0, _tslib.__generator)(this, function (_f) {
|
1235 | switch (_f.label) {
|
1236 | case 0:
|
1237 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(mutation, 9) : (0, _tsInvariant.invariant)(mutation, 'mutation option is required. You must specify your GraphQL document in the mutation option.');
|
1238 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(!fetchPolicy || fetchPolicy === 'no-cache', 10) : (0, _tsInvariant.invariant)(!fetchPolicy || fetchPolicy === 'no-cache', "Mutations only support a 'no-cache' fetchPolicy. If you don't want to disable the cache, remove your fetchPolicy setting to proceed with the default mutation behavior.");
|
1239 | mutationId = this.generateQueryId();
|
1240 | mutation = this.transform(mutation).document;
|
1241 | this.setQuery(mutationId, function () {
|
1242 | return {
|
1243 | document: mutation
|
1244 | };
|
1245 | });
|
1246 | variables = this.getVariables(mutation, variables);
|
1247 | if (!this.transform(mutation).hasClientExports) return [3, 2];
|
1248 | return [4, this.localState.addExportedVariables(mutation, variables, context)];
|
1249 |
|
1250 | case 1:
|
1251 | variables = _f.sent();
|
1252 | _f.label = 2;
|
1253 |
|
1254 | case 2:
|
1255 | generateUpdateQueriesInfo = function () {
|
1256 | var ret = {};
|
1257 |
|
1258 | if (updateQueriesByName) {
|
1259 | _this.queries.forEach(function (_a, queryId) {
|
1260 | var observableQuery = _a.observableQuery;
|
1261 |
|
1262 | if (observableQuery) {
|
1263 | var queryName = observableQuery.queryName;
|
1264 |
|
1265 | if (queryName && hasOwnProperty.call(updateQueriesByName, queryName)) {
|
1266 | ret[queryId] = {
|
1267 | updater: updateQueriesByName[queryName],
|
1268 | query: _this.queryStore.get(queryId)
|
1269 | };
|
1270 | }
|
1271 | }
|
1272 | });
|
1273 | }
|
1274 |
|
1275 | return ret;
|
1276 | };
|
1277 |
|
1278 | this.mutationStore.initMutation(mutationId, mutation, variables);
|
1279 | this.dataStore.markMutationInit({
|
1280 | mutationId: mutationId,
|
1281 | document: mutation,
|
1282 | variables: variables,
|
1283 | updateQueries: generateUpdateQueriesInfo(),
|
1284 | update: updateWithProxyFn,
|
1285 | optimisticResponse: optimisticResponse
|
1286 | });
|
1287 | this.broadcastQueries();
|
1288 | self = this;
|
1289 | return [2, new Promise(function (resolve, reject) {
|
1290 | var storeResult;
|
1291 | var error;
|
1292 | self.getObservableFromLink(mutation, (0, _tslib.__assign)((0, _tslib.__assign)({}, context), {
|
1293 | optimisticResponse: optimisticResponse
|
1294 | }), variables, false).subscribe({
|
1295 | next: function (result) {
|
1296 | if ((0, _apolloUtilities.graphQLResultHasError)(result) && errorPolicy === 'none') {
|
1297 | error = new ApolloError({
|
1298 | graphQLErrors: result.errors
|
1299 | });
|
1300 | return;
|
1301 | }
|
1302 |
|
1303 | self.mutationStore.markMutationResult(mutationId);
|
1304 |
|
1305 | if (fetchPolicy !== 'no-cache') {
|
1306 | self.dataStore.markMutationResult({
|
1307 | mutationId: mutationId,
|
1308 | result: result,
|
1309 | document: mutation,
|
1310 | variables: variables,
|
1311 | updateQueries: generateUpdateQueriesInfo(),
|
1312 | update: updateWithProxyFn
|
1313 | });
|
1314 | }
|
1315 |
|
1316 | storeResult = result;
|
1317 | },
|
1318 | error: function (err) {
|
1319 | self.mutationStore.markMutationError(mutationId, err);
|
1320 | self.dataStore.markMutationComplete({
|
1321 | mutationId: mutationId,
|
1322 | optimisticResponse: optimisticResponse
|
1323 | });
|
1324 | self.broadcastQueries();
|
1325 | self.setQuery(mutationId, function () {
|
1326 | return {
|
1327 | document: null
|
1328 | };
|
1329 | });
|
1330 | reject(new ApolloError({
|
1331 | networkError: err
|
1332 | }));
|
1333 | },
|
1334 | complete: function () {
|
1335 | if (error) {
|
1336 | self.mutationStore.markMutationError(mutationId, error);
|
1337 | }
|
1338 |
|
1339 | self.dataStore.markMutationComplete({
|
1340 | mutationId: mutationId,
|
1341 | optimisticResponse: optimisticResponse
|
1342 | });
|
1343 | self.broadcastQueries();
|
1344 |
|
1345 | if (error) {
|
1346 | reject(error);
|
1347 | return;
|
1348 | }
|
1349 |
|
1350 | if (typeof refetchQueries === 'function') {
|
1351 | refetchQueries = refetchQueries(storeResult);
|
1352 | }
|
1353 |
|
1354 | var refetchQueryPromises = [];
|
1355 |
|
1356 | if (isNonEmptyArray(refetchQueries)) {
|
1357 | refetchQueries.forEach(function (refetchQuery) {
|
1358 | if (typeof refetchQuery === 'string') {
|
1359 | self.queries.forEach(function (_a) {
|
1360 | var observableQuery = _a.observableQuery;
|
1361 |
|
1362 | if (observableQuery && observableQuery.queryName === refetchQuery) {
|
1363 | refetchQueryPromises.push(observableQuery.refetch());
|
1364 | }
|
1365 | });
|
1366 | } else {
|
1367 | var queryOptions = {
|
1368 | query: refetchQuery.query,
|
1369 | variables: refetchQuery.variables,
|
1370 | fetchPolicy: 'network-only'
|
1371 | };
|
1372 |
|
1373 | if (refetchQuery.context) {
|
1374 | queryOptions.context = refetchQuery.context;
|
1375 | }
|
1376 |
|
1377 | refetchQueryPromises.push(self.query(queryOptions));
|
1378 | }
|
1379 | });
|
1380 | }
|
1381 |
|
1382 | Promise.all(awaitRefetchQueries ? refetchQueryPromises : []).then(function () {
|
1383 | self.setQuery(mutationId, function () {
|
1384 | return {
|
1385 | document: null
|
1386 | };
|
1387 | });
|
1388 |
|
1389 | if (errorPolicy === 'ignore' && storeResult && (0, _apolloUtilities.graphQLResultHasError)(storeResult)) {
|
1390 | delete storeResult.errors;
|
1391 | }
|
1392 |
|
1393 | resolve(storeResult);
|
1394 | });
|
1395 | }
|
1396 | });
|
1397 | })];
|
1398 | }
|
1399 | });
|
1400 | });
|
1401 | };
|
1402 |
|
1403 | QueryManager.prototype.fetchQuery = function (queryId, options, fetchType, fetchMoreForQueryId) {
|
1404 | return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
|
1405 | var _a, metadata, _b, fetchPolicy, _c, context, query, variables, storeResult, isNetworkOnly, needToFetch, _d, complete, result, shouldFetch, requestId, cancel, networkResult;
|
1406 |
|
1407 | var _this = this;
|
1408 |
|
1409 | return (0, _tslib.__generator)(this, function (_e) {
|
1410 | switch (_e.label) {
|
1411 | case 0:
|
1412 | _a = options.metadata, metadata = _a === void 0 ? null : _a, _b = options.fetchPolicy, fetchPolicy = _b === void 0 ? 'cache-first' : _b, _c = options.context, context = _c === void 0 ? {} : _c;
|
1413 | query = this.transform(options.query).document;
|
1414 | variables = this.getVariables(query, options.variables);
|
1415 | if (!this.transform(query).hasClientExports) return [3, 2];
|
1416 | return [4, this.localState.addExportedVariables(query, variables, context)];
|
1417 |
|
1418 | case 1:
|
1419 | variables = _e.sent();
|
1420 | _e.label = 2;
|
1421 |
|
1422 | case 2:
|
1423 | options = (0, _tslib.__assign)((0, _tslib.__assign)({}, options), {
|
1424 | variables: variables
|
1425 | });
|
1426 | isNetworkOnly = fetchPolicy === 'network-only' || fetchPolicy === 'no-cache';
|
1427 | needToFetch = isNetworkOnly;
|
1428 |
|
1429 | if (!isNetworkOnly) {
|
1430 | _d = this.dataStore.getCache().diff({
|
1431 | query: query,
|
1432 | variables: variables,
|
1433 | returnPartialData: true,
|
1434 | optimistic: false
|
1435 | }), complete = _d.complete, result = _d.result;
|
1436 | needToFetch = !complete || fetchPolicy === 'cache-and-network';
|
1437 | storeResult = result;
|
1438 | }
|
1439 |
|
1440 | shouldFetch = needToFetch && fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby';
|
1441 | if ((0, _apolloUtilities.hasDirectives)(['live'], query)) shouldFetch = true;
|
1442 | requestId = this.idCounter++;
|
1443 | cancel = fetchPolicy !== 'no-cache' ? this.updateQueryWatch(queryId, query, options) : undefined;
|
1444 | this.setQuery(queryId, function () {
|
1445 | return {
|
1446 | document: query,
|
1447 | lastRequestId: requestId,
|
1448 | invalidated: true,
|
1449 | cancel: cancel
|
1450 | };
|
1451 | });
|
1452 | this.invalidate(fetchMoreForQueryId);
|
1453 | this.queryStore.initQuery({
|
1454 | queryId: queryId,
|
1455 | document: query,
|
1456 | storePreviousVariables: shouldFetch,
|
1457 | variables: variables,
|
1458 | isPoll: fetchType === FetchType.poll,
|
1459 | isRefetch: fetchType === FetchType.refetch,
|
1460 | metadata: metadata,
|
1461 | fetchMoreForQueryId: fetchMoreForQueryId
|
1462 | });
|
1463 | this.broadcastQueries();
|
1464 |
|
1465 | if (shouldFetch) {
|
1466 | networkResult = this.fetchRequest({
|
1467 | requestId: requestId,
|
1468 | queryId: queryId,
|
1469 | document: query,
|
1470 | options: options,
|
1471 | fetchMoreForQueryId: fetchMoreForQueryId
|
1472 | }).catch(function (error) {
|
1473 | if (isApolloError(error)) {
|
1474 | throw error;
|
1475 | } else {
|
1476 | if (requestId >= _this.getQuery(queryId).lastRequestId) {
|
1477 | _this.queryStore.markQueryError(queryId, error, fetchMoreForQueryId);
|
1478 |
|
1479 | _this.invalidate(queryId);
|
1480 |
|
1481 | _this.invalidate(fetchMoreForQueryId);
|
1482 |
|
1483 | _this.broadcastQueries();
|
1484 | }
|
1485 |
|
1486 | throw new ApolloError({
|
1487 | networkError: error
|
1488 | });
|
1489 | }
|
1490 | });
|
1491 |
|
1492 | if (fetchPolicy !== 'cache-and-network') {
|
1493 | return [2, networkResult];
|
1494 | }
|
1495 |
|
1496 | networkResult.catch(function () {});
|
1497 | }
|
1498 |
|
1499 | this.queryStore.markQueryResultClient(queryId, !shouldFetch);
|
1500 | this.invalidate(queryId);
|
1501 | this.invalidate(fetchMoreForQueryId);
|
1502 |
|
1503 | if (this.transform(query).hasForcedResolvers) {
|
1504 | return [2, this.localState.runResolvers({
|
1505 | document: query,
|
1506 | remoteResult: {
|
1507 | data: storeResult
|
1508 | },
|
1509 | context: context,
|
1510 | variables: variables,
|
1511 | onlyRunForcedResolvers: true
|
1512 | }).then(function (result) {
|
1513 | _this.markQueryResult(queryId, result, options, fetchMoreForQueryId);
|
1514 |
|
1515 | _this.broadcastQueries();
|
1516 |
|
1517 | return result;
|
1518 | })];
|
1519 | }
|
1520 |
|
1521 | this.broadcastQueries();
|
1522 | return [2, {
|
1523 | data: storeResult
|
1524 | }];
|
1525 | }
|
1526 | });
|
1527 | });
|
1528 | };
|
1529 |
|
1530 | QueryManager.prototype.markQueryResult = function (queryId, result, _a, fetchMoreForQueryId) {
|
1531 | var fetchPolicy = _a.fetchPolicy,
|
1532 | variables = _a.variables,
|
1533 | errorPolicy = _a.errorPolicy;
|
1534 |
|
1535 | if (fetchPolicy === 'no-cache') {
|
1536 | this.setQuery(queryId, function () {
|
1537 | return {
|
1538 | newData: {
|
1539 | result: result.data,
|
1540 | complete: true
|
1541 | }
|
1542 | };
|
1543 | });
|
1544 | } else {
|
1545 | this.dataStore.markQueryResult(result, this.getQuery(queryId).document, variables, fetchMoreForQueryId, errorPolicy === 'ignore' || errorPolicy === 'all');
|
1546 | }
|
1547 | };
|
1548 |
|
1549 | QueryManager.prototype.queryListenerForObserver = function (queryId, options, observer) {
|
1550 | var _this = this;
|
1551 |
|
1552 | function invoke(method, argument) {
|
1553 | if (observer[method]) {
|
1554 | try {
|
1555 | observer[method](argument);
|
1556 | } catch (e) {
|
1557 | process.env.NODE_ENV === "production" || _tsInvariant.invariant.error(e);
|
1558 | }
|
1559 | } else if (method === 'error') {
|
1560 | process.env.NODE_ENV === "production" || _tsInvariant.invariant.error(argument);
|
1561 | }
|
1562 | }
|
1563 |
|
1564 | return function (queryStoreValue, newData) {
|
1565 | _this.invalidate(queryId, false);
|
1566 |
|
1567 | if (!queryStoreValue) return;
|
1568 |
|
1569 | var _a = _this.getQuery(queryId),
|
1570 | observableQuery = _a.observableQuery,
|
1571 | document = _a.document;
|
1572 |
|
1573 | var fetchPolicy = observableQuery ? observableQuery.options.fetchPolicy : options.fetchPolicy;
|
1574 | if (fetchPolicy === 'standby') return;
|
1575 | var loading = isNetworkRequestInFlight(queryStoreValue.networkStatus);
|
1576 | var lastResult = observableQuery && observableQuery.getLastResult();
|
1577 | var networkStatusChanged = !!(lastResult && lastResult.networkStatus !== queryStoreValue.networkStatus);
|
1578 | var shouldNotifyIfLoading = options.returnPartialData || !newData && queryStoreValue.previousVariables || networkStatusChanged && options.notifyOnNetworkStatusChange || fetchPolicy === 'cache-only' || fetchPolicy === 'cache-and-network';
|
1579 |
|
1580 | if (loading && !shouldNotifyIfLoading) {
|
1581 | return;
|
1582 | }
|
1583 |
|
1584 | var hasGraphQLErrors = isNonEmptyArray(queryStoreValue.graphQLErrors);
|
1585 | var errorPolicy = observableQuery && observableQuery.options.errorPolicy || options.errorPolicy || 'none';
|
1586 |
|
1587 | if (errorPolicy === 'none' && hasGraphQLErrors || queryStoreValue.networkError) {
|
1588 | return invoke('error', new ApolloError({
|
1589 | graphQLErrors: queryStoreValue.graphQLErrors,
|
1590 | networkError: queryStoreValue.networkError
|
1591 | }));
|
1592 | }
|
1593 |
|
1594 | try {
|
1595 | var data = void 0;
|
1596 | var isMissing = void 0;
|
1597 |
|
1598 | if (newData) {
|
1599 | if (fetchPolicy !== 'no-cache' && fetchPolicy !== 'network-only') {
|
1600 | _this.setQuery(queryId, function () {
|
1601 | return {
|
1602 | newData: null
|
1603 | };
|
1604 | });
|
1605 | }
|
1606 |
|
1607 | data = newData.result;
|
1608 | isMissing = !newData.complete;
|
1609 | } else {
|
1610 | var lastError = observableQuery && observableQuery.getLastError();
|
1611 | var errorStatusChanged = errorPolicy !== 'none' && (lastError && lastError.graphQLErrors) !== queryStoreValue.graphQLErrors;
|
1612 |
|
1613 | if (lastResult && lastResult.data && !errorStatusChanged) {
|
1614 | data = lastResult.data;
|
1615 | isMissing = false;
|
1616 | } else {
|
1617 | var diffResult = _this.dataStore.getCache().diff({
|
1618 | query: document,
|
1619 | variables: queryStoreValue.previousVariables || queryStoreValue.variables,
|
1620 | returnPartialData: true,
|
1621 | optimistic: true
|
1622 | });
|
1623 |
|
1624 | data = diffResult.result;
|
1625 | isMissing = !diffResult.complete;
|
1626 | }
|
1627 | }
|
1628 |
|
1629 | var stale = isMissing && !(options.returnPartialData || fetchPolicy === 'cache-only');
|
1630 | var resultFromStore = {
|
1631 | data: stale ? lastResult && lastResult.data : data,
|
1632 | loading: loading,
|
1633 | networkStatus: queryStoreValue.networkStatus,
|
1634 | stale: stale
|
1635 | };
|
1636 |
|
1637 | if (errorPolicy === 'all' && hasGraphQLErrors) {
|
1638 | resultFromStore.errors = queryStoreValue.graphQLErrors;
|
1639 | }
|
1640 |
|
1641 | invoke('next', resultFromStore);
|
1642 | } catch (networkError) {
|
1643 | invoke('error', new ApolloError({
|
1644 | networkError: networkError
|
1645 | }));
|
1646 | }
|
1647 | };
|
1648 | };
|
1649 |
|
1650 | QueryManager.prototype.transform = function (document) {
|
1651 | var transformCache = this.transformCache;
|
1652 |
|
1653 | if (!transformCache.has(document)) {
|
1654 | var cache = this.dataStore.getCache();
|
1655 | var transformed = cache.transformDocument(document);
|
1656 | var forLink = (0, _apolloUtilities.removeConnectionDirectiveFromDocument)(cache.transformForLink(transformed));
|
1657 | var clientQuery = this.localState.clientQuery(transformed);
|
1658 | var serverQuery = this.localState.serverQuery(forLink);
|
1659 | var cacheEntry_1 = {
|
1660 | document: transformed,
|
1661 | hasClientExports: (0, _apolloUtilities.hasClientExports)(transformed),
|
1662 | hasForcedResolvers: this.localState.shouldForceResolvers(transformed),
|
1663 | clientQuery: clientQuery,
|
1664 | serverQuery: serverQuery,
|
1665 | defaultVars: (0, _apolloUtilities.getDefaultValues)((0, _apolloUtilities.getOperationDefinition)(transformed))
|
1666 | };
|
1667 |
|
1668 | var add = function (doc) {
|
1669 | if (doc && !transformCache.has(doc)) {
|
1670 | transformCache.set(doc, cacheEntry_1);
|
1671 | }
|
1672 | };
|
1673 |
|
1674 | add(document);
|
1675 | add(transformed);
|
1676 | add(clientQuery);
|
1677 | add(serverQuery);
|
1678 | }
|
1679 |
|
1680 | return transformCache.get(document);
|
1681 | };
|
1682 |
|
1683 | QueryManager.prototype.getVariables = function (document, variables) {
|
1684 | return (0, _tslib.__assign)((0, _tslib.__assign)({}, this.transform(document).defaultVars), variables);
|
1685 | };
|
1686 |
|
1687 | QueryManager.prototype.watchQuery = function (options, shouldSubscribe) {
|
1688 | if (shouldSubscribe === void 0) {
|
1689 | shouldSubscribe = true;
|
1690 | }
|
1691 |
|
1692 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(options.fetchPolicy !== 'standby', 11) : (0, _tsInvariant.invariant)(options.fetchPolicy !== 'standby', 'client.watchQuery cannot be called with fetchPolicy set to "standby"');
|
1693 | options.variables = this.getVariables(options.query, options.variables);
|
1694 |
|
1695 | if (typeof options.notifyOnNetworkStatusChange === 'undefined') {
|
1696 | options.notifyOnNetworkStatusChange = false;
|
1697 | }
|
1698 |
|
1699 | var transformedOptions = (0, _tslib.__assign)({}, options);
|
1700 | return new ObservableQuery({
|
1701 | queryManager: this,
|
1702 | options: transformedOptions,
|
1703 | shouldSubscribe: shouldSubscribe
|
1704 | });
|
1705 | };
|
1706 |
|
1707 | QueryManager.prototype.query = function (options) {
|
1708 | var _this = this;
|
1709 |
|
1710 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(options.query, 12) : (0, _tsInvariant.invariant)(options.query, 'query option is required. You must specify your GraphQL document ' + 'in the query option.');
|
1711 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(options.query.kind === 'Document', 13) : (0, _tsInvariant.invariant)(options.query.kind === 'Document', 'You must wrap the query string in a "gql" tag.');
|
1712 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(!options.returnPartialData, 14) : (0, _tsInvariant.invariant)(!options.returnPartialData, 'returnPartialData option only supported on watchQuery.');
|
1713 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(!options.pollInterval, 15) : (0, _tsInvariant.invariant)(!options.pollInterval, 'pollInterval option only supported on watchQuery.');
|
1714 | return new Promise(function (resolve, reject) {
|
1715 | var watchedQuery = _this.watchQuery(options, false);
|
1716 |
|
1717 | _this.fetchQueryRejectFns.set("query:" + watchedQuery.queryId, reject);
|
1718 |
|
1719 | watchedQuery.result().then(resolve, reject).then(function () {
|
1720 | return _this.fetchQueryRejectFns.delete("query:" + watchedQuery.queryId);
|
1721 | });
|
1722 | });
|
1723 | };
|
1724 |
|
1725 | QueryManager.prototype.generateQueryId = function () {
|
1726 | return String(this.idCounter++);
|
1727 | };
|
1728 |
|
1729 | QueryManager.prototype.stopQueryInStore = function (queryId) {
|
1730 | this.stopQueryInStoreNoBroadcast(queryId);
|
1731 | this.broadcastQueries();
|
1732 | };
|
1733 |
|
1734 | QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {
|
1735 | this.stopPollingQuery(queryId);
|
1736 | this.queryStore.stopQuery(queryId);
|
1737 | this.invalidate(queryId);
|
1738 | };
|
1739 |
|
1740 | QueryManager.prototype.addQueryListener = function (queryId, listener) {
|
1741 | this.setQuery(queryId, function (_a) {
|
1742 | var listeners = _a.listeners;
|
1743 | listeners.add(listener);
|
1744 | return {
|
1745 | invalidated: false
|
1746 | };
|
1747 | });
|
1748 | };
|
1749 |
|
1750 | QueryManager.prototype.updateQueryWatch = function (queryId, document, options) {
|
1751 | var _this = this;
|
1752 |
|
1753 | var cancel = this.getQuery(queryId).cancel;
|
1754 | if (cancel) cancel();
|
1755 |
|
1756 | var previousResult = function () {
|
1757 | var previousResult = null;
|
1758 |
|
1759 | var observableQuery = _this.getQuery(queryId).observableQuery;
|
1760 |
|
1761 | if (observableQuery) {
|
1762 | var lastResult = observableQuery.getLastResult();
|
1763 |
|
1764 | if (lastResult) {
|
1765 | previousResult = lastResult.data;
|
1766 | }
|
1767 | }
|
1768 |
|
1769 | return previousResult;
|
1770 | };
|
1771 |
|
1772 | return this.dataStore.getCache().watch({
|
1773 | query: document,
|
1774 | variables: options.variables,
|
1775 | optimistic: true,
|
1776 | previousResult: previousResult,
|
1777 | callback: function (newData) {
|
1778 | _this.setQuery(queryId, function () {
|
1779 | return {
|
1780 | invalidated: true,
|
1781 | newData: newData
|
1782 | };
|
1783 | });
|
1784 | }
|
1785 | });
|
1786 | };
|
1787 |
|
1788 | QueryManager.prototype.addObservableQuery = function (queryId, observableQuery) {
|
1789 | this.setQuery(queryId, function () {
|
1790 | return {
|
1791 | observableQuery: observableQuery
|
1792 | };
|
1793 | });
|
1794 | };
|
1795 |
|
1796 | QueryManager.prototype.removeObservableQuery = function (queryId) {
|
1797 | var cancel = this.getQuery(queryId).cancel;
|
1798 | this.setQuery(queryId, function () {
|
1799 | return {
|
1800 | observableQuery: null
|
1801 | };
|
1802 | });
|
1803 | if (cancel) cancel();
|
1804 | };
|
1805 |
|
1806 | QueryManager.prototype.clearStore = function () {
|
1807 | this.fetchQueryRejectFns.forEach(function (reject) {
|
1808 | reject(process.env.NODE_ENV === "production" ? new _tsInvariant.InvariantError(16) : new _tsInvariant.InvariantError('Store reset while query was in flight (not completed in link chain)'));
|
1809 | });
|
1810 | var resetIds = [];
|
1811 | this.queries.forEach(function (_a, queryId) {
|
1812 | var observableQuery = _a.observableQuery;
|
1813 | if (observableQuery) resetIds.push(queryId);
|
1814 | });
|
1815 | this.queryStore.reset(resetIds);
|
1816 | this.mutationStore.reset();
|
1817 | return this.dataStore.reset();
|
1818 | };
|
1819 |
|
1820 | QueryManager.prototype.resetStore = function () {
|
1821 | var _this = this;
|
1822 |
|
1823 | return this.clearStore().then(function () {
|
1824 | return _this.reFetchObservableQueries();
|
1825 | });
|
1826 | };
|
1827 |
|
1828 | QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {
|
1829 | var _this = this;
|
1830 |
|
1831 | if (includeStandby === void 0) {
|
1832 | includeStandby = false;
|
1833 | }
|
1834 |
|
1835 | var observableQueryPromises = [];
|
1836 | this.queries.forEach(function (_a, queryId) {
|
1837 | var observableQuery = _a.observableQuery;
|
1838 |
|
1839 | if (observableQuery) {
|
1840 | var fetchPolicy = observableQuery.options.fetchPolicy;
|
1841 | observableQuery.resetLastResults();
|
1842 |
|
1843 | if (fetchPolicy !== 'cache-only' && (includeStandby || fetchPolicy !== 'standby')) {
|
1844 | observableQueryPromises.push(observableQuery.refetch());
|
1845 | }
|
1846 |
|
1847 | _this.setQuery(queryId, function () {
|
1848 | return {
|
1849 | newData: null
|
1850 | };
|
1851 | });
|
1852 |
|
1853 | _this.invalidate(queryId);
|
1854 | }
|
1855 | });
|
1856 | this.broadcastQueries();
|
1857 | return Promise.all(observableQueryPromises);
|
1858 | };
|
1859 |
|
1860 | QueryManager.prototype.observeQuery = function (queryId, options, observer) {
|
1861 | this.addQueryListener(queryId, this.queryListenerForObserver(queryId, options, observer));
|
1862 | return this.fetchQuery(queryId, options);
|
1863 | };
|
1864 |
|
1865 | QueryManager.prototype.startQuery = function (queryId, options, listener) {
|
1866 | process.env.NODE_ENV === "production" || _tsInvariant.invariant.warn("The QueryManager.startQuery method has been deprecated");
|
1867 | this.addQueryListener(queryId, listener);
|
1868 | this.fetchQuery(queryId, options).catch(function () {
|
1869 | return undefined;
|
1870 | });
|
1871 | return queryId;
|
1872 | };
|
1873 |
|
1874 | QueryManager.prototype.startGraphQLSubscription = function (_a) {
|
1875 | var _this = this;
|
1876 |
|
1877 | var query = _a.query,
|
1878 | fetchPolicy = _a.fetchPolicy,
|
1879 | variables = _a.variables;
|
1880 | query = this.transform(query).document;
|
1881 | variables = this.getVariables(query, variables);
|
1882 |
|
1883 | var makeObservable = function (variables) {
|
1884 | return _this.getObservableFromLink(query, {}, variables, false).map(function (result) {
|
1885 | if (!fetchPolicy || fetchPolicy !== 'no-cache') {
|
1886 | _this.dataStore.markSubscriptionResult(result, query, variables);
|
1887 |
|
1888 | _this.broadcastQueries();
|
1889 | }
|
1890 |
|
1891 | if ((0, _apolloUtilities.graphQLResultHasError)(result)) {
|
1892 | throw new ApolloError({
|
1893 | graphQLErrors: result.errors
|
1894 | });
|
1895 | }
|
1896 |
|
1897 | return result;
|
1898 | });
|
1899 | };
|
1900 |
|
1901 | if (this.transform(query).hasClientExports) {
|
1902 | var observablePromise_1 = this.localState.addExportedVariables(query, variables).then(makeObservable);
|
1903 | return new Observable(function (observer) {
|
1904 | var sub = null;
|
1905 | observablePromise_1.then(function (observable) {
|
1906 | return sub = observable.subscribe(observer);
|
1907 | }, observer.error);
|
1908 | return function () {
|
1909 | return sub && sub.unsubscribe();
|
1910 | };
|
1911 | });
|
1912 | }
|
1913 |
|
1914 | return makeObservable(variables);
|
1915 | };
|
1916 |
|
1917 | QueryManager.prototype.stopQuery = function (queryId) {
|
1918 | this.stopQueryNoBroadcast(queryId);
|
1919 | this.broadcastQueries();
|
1920 | };
|
1921 |
|
1922 | QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {
|
1923 | this.stopQueryInStoreNoBroadcast(queryId);
|
1924 | this.removeQuery(queryId);
|
1925 | };
|
1926 |
|
1927 | QueryManager.prototype.removeQuery = function (queryId) {
|
1928 | this.fetchQueryRejectFns.delete("query:" + queryId);
|
1929 | this.fetchQueryRejectFns.delete("fetchRequest:" + queryId);
|
1930 | this.getQuery(queryId).subscriptions.forEach(function (x) {
|
1931 | return x.unsubscribe();
|
1932 | });
|
1933 | this.queries.delete(queryId);
|
1934 | };
|
1935 |
|
1936 | QueryManager.prototype.getCurrentQueryResult = function (observableQuery, optimistic) {
|
1937 | if (optimistic === void 0) {
|
1938 | optimistic = true;
|
1939 | }
|
1940 |
|
1941 | var _a = observableQuery.options,
|
1942 | variables = _a.variables,
|
1943 | query = _a.query,
|
1944 | fetchPolicy = _a.fetchPolicy,
|
1945 | returnPartialData = _a.returnPartialData;
|
1946 | var lastResult = observableQuery.getLastResult();
|
1947 | var newData = this.getQuery(observableQuery.queryId).newData;
|
1948 |
|
1949 | if (newData && newData.complete) {
|
1950 | return {
|
1951 | data: newData.result,
|
1952 | partial: false
|
1953 | };
|
1954 | }
|
1955 |
|
1956 | if (fetchPolicy === 'no-cache' || fetchPolicy === 'network-only') {
|
1957 | return {
|
1958 | data: undefined,
|
1959 | partial: false
|
1960 | };
|
1961 | }
|
1962 |
|
1963 | var _b = this.dataStore.getCache().diff({
|
1964 | query: query,
|
1965 | variables: variables,
|
1966 | previousResult: lastResult ? lastResult.data : undefined,
|
1967 | returnPartialData: true,
|
1968 | optimistic: optimistic
|
1969 | }),
|
1970 | result = _b.result,
|
1971 | complete = _b.complete;
|
1972 |
|
1973 | return {
|
1974 | data: complete || returnPartialData ? result : void 0,
|
1975 | partial: !complete
|
1976 | };
|
1977 | };
|
1978 |
|
1979 | QueryManager.prototype.getQueryWithPreviousResult = function (queryIdOrObservable) {
|
1980 | var observableQuery;
|
1981 |
|
1982 | if (typeof queryIdOrObservable === 'string') {
|
1983 | var foundObserveableQuery = this.getQuery(queryIdOrObservable).observableQuery;
|
1984 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(foundObserveableQuery, 17) : (0, _tsInvariant.invariant)(foundObserveableQuery, "ObservableQuery with this id doesn't exist: " + queryIdOrObservable);
|
1985 | observableQuery = foundObserveableQuery;
|
1986 | } else {
|
1987 | observableQuery = queryIdOrObservable;
|
1988 | }
|
1989 |
|
1990 | var _a = observableQuery.options,
|
1991 | variables = _a.variables,
|
1992 | query = _a.query;
|
1993 | return {
|
1994 | previousResult: this.getCurrentQueryResult(observableQuery, false).data,
|
1995 | variables: variables,
|
1996 | document: query
|
1997 | };
|
1998 | };
|
1999 |
|
2000 | QueryManager.prototype.broadcastQueries = function () {
|
2001 | var _this = this;
|
2002 |
|
2003 | this.onBroadcast();
|
2004 | this.queries.forEach(function (info, id) {
|
2005 | if (info.invalidated) {
|
2006 | info.listeners.forEach(function (listener) {
|
2007 | if (listener) {
|
2008 | listener(_this.queryStore.get(id), info.newData);
|
2009 | }
|
2010 | });
|
2011 | }
|
2012 | });
|
2013 | };
|
2014 |
|
2015 | QueryManager.prototype.getLocalState = function () {
|
2016 | return this.localState;
|
2017 | };
|
2018 |
|
2019 | QueryManager.prototype.getObservableFromLink = function (query, context, variables, deduplication) {
|
2020 | var _this = this;
|
2021 |
|
2022 | if (deduplication === void 0) {
|
2023 | deduplication = this.queryDeduplication;
|
2024 | }
|
2025 |
|
2026 | var observable;
|
2027 | var serverQuery = this.transform(query).serverQuery;
|
2028 |
|
2029 | if (serverQuery) {
|
2030 | var _a = this,
|
2031 | inFlightLinkObservables_1 = _a.inFlightLinkObservables,
|
2032 | link = _a.link;
|
2033 |
|
2034 | var operation = {
|
2035 | query: serverQuery,
|
2036 | variables: variables,
|
2037 | operationName: (0, _apolloUtilities.getOperationName)(serverQuery) || void 0,
|
2038 | context: this.prepareContext((0, _tslib.__assign)((0, _tslib.__assign)({}, context), {
|
2039 | forceFetch: !deduplication
|
2040 | }))
|
2041 | };
|
2042 | context = operation.context;
|
2043 |
|
2044 | if (deduplication) {
|
2045 | var byVariables_1 = inFlightLinkObservables_1.get(serverQuery) || new Map();
|
2046 | inFlightLinkObservables_1.set(serverQuery, byVariables_1);
|
2047 | var varJson_1 = JSON.stringify(variables);
|
2048 | observable = byVariables_1.get(varJson_1);
|
2049 |
|
2050 | if (!observable) {
|
2051 | byVariables_1.set(varJson_1, observable = multiplex((0, _apolloLink.execute)(link, operation)));
|
2052 |
|
2053 | var cleanup = function () {
|
2054 | byVariables_1.delete(varJson_1);
|
2055 | if (!byVariables_1.size) inFlightLinkObservables_1.delete(serverQuery);
|
2056 | cleanupSub_1.unsubscribe();
|
2057 | };
|
2058 |
|
2059 | var cleanupSub_1 = observable.subscribe({
|
2060 | next: cleanup,
|
2061 | error: cleanup,
|
2062 | complete: cleanup
|
2063 | });
|
2064 | }
|
2065 | } else {
|
2066 | observable = multiplex((0, _apolloLink.execute)(link, operation));
|
2067 | }
|
2068 | } else {
|
2069 | observable = Observable.of({
|
2070 | data: {}
|
2071 | });
|
2072 | context = this.prepareContext(context);
|
2073 | }
|
2074 |
|
2075 | var clientQuery = this.transform(query).clientQuery;
|
2076 |
|
2077 | if (clientQuery) {
|
2078 | observable = asyncMap(observable, function (result) {
|
2079 | return _this.localState.runResolvers({
|
2080 | document: clientQuery,
|
2081 | remoteResult: result,
|
2082 | context: context,
|
2083 | variables: variables
|
2084 | });
|
2085 | });
|
2086 | }
|
2087 |
|
2088 | return observable;
|
2089 | };
|
2090 |
|
2091 | QueryManager.prototype.fetchRequest = function (_a) {
|
2092 | var _this = this;
|
2093 |
|
2094 | var requestId = _a.requestId,
|
2095 | queryId = _a.queryId,
|
2096 | document = _a.document,
|
2097 | options = _a.options,
|
2098 | fetchMoreForQueryId = _a.fetchMoreForQueryId;
|
2099 | var variables = options.variables,
|
2100 | _b = options.errorPolicy,
|
2101 | errorPolicy = _b === void 0 ? 'none' : _b,
|
2102 | fetchPolicy = options.fetchPolicy;
|
2103 | var resultFromStore;
|
2104 | var errorsFromStore;
|
2105 | return new Promise(function (resolve, reject) {
|
2106 | var observable = _this.getObservableFromLink(document, options.context, variables);
|
2107 |
|
2108 | var fqrfId = "fetchRequest:" + queryId;
|
2109 |
|
2110 | _this.fetchQueryRejectFns.set(fqrfId, reject);
|
2111 |
|
2112 | var cleanup = function () {
|
2113 | _this.fetchQueryRejectFns.delete(fqrfId);
|
2114 |
|
2115 | _this.setQuery(queryId, function (_a) {
|
2116 | var subscriptions = _a.subscriptions;
|
2117 | subscriptions.delete(subscription);
|
2118 | });
|
2119 | };
|
2120 |
|
2121 | var subscription = observable.map(function (result) {
|
2122 | if (requestId >= _this.getQuery(queryId).lastRequestId) {
|
2123 | _this.markQueryResult(queryId, result, options, fetchMoreForQueryId);
|
2124 |
|
2125 | _this.queryStore.markQueryResult(queryId, result, fetchMoreForQueryId);
|
2126 |
|
2127 | _this.invalidate(queryId);
|
2128 |
|
2129 | _this.invalidate(fetchMoreForQueryId);
|
2130 |
|
2131 | _this.broadcastQueries();
|
2132 | }
|
2133 |
|
2134 | if (errorPolicy === 'none' && isNonEmptyArray(result.errors)) {
|
2135 | return reject(new ApolloError({
|
2136 | graphQLErrors: result.errors
|
2137 | }));
|
2138 | }
|
2139 |
|
2140 | if (errorPolicy === 'all') {
|
2141 | errorsFromStore = result.errors;
|
2142 | }
|
2143 |
|
2144 | if (fetchMoreForQueryId || fetchPolicy === 'no-cache') {
|
2145 | resultFromStore = result.data;
|
2146 | } else {
|
2147 | var _a = _this.dataStore.getCache().diff({
|
2148 | variables: variables,
|
2149 | query: document,
|
2150 | optimistic: false,
|
2151 | returnPartialData: true
|
2152 | }),
|
2153 | result_1 = _a.result,
|
2154 | complete = _a.complete;
|
2155 |
|
2156 | if (complete || options.returnPartialData) {
|
2157 | resultFromStore = result_1;
|
2158 | }
|
2159 | }
|
2160 | }).subscribe({
|
2161 | error: function (error) {
|
2162 | cleanup();
|
2163 | reject(error);
|
2164 | },
|
2165 | complete: function () {
|
2166 | cleanup();
|
2167 | resolve({
|
2168 | data: resultFromStore,
|
2169 | errors: errorsFromStore,
|
2170 | loading: false,
|
2171 | networkStatus: NetworkStatus.ready,
|
2172 | stale: false
|
2173 | });
|
2174 | }
|
2175 | });
|
2176 |
|
2177 | _this.setQuery(queryId, function (_a) {
|
2178 | var subscriptions = _a.subscriptions;
|
2179 | subscriptions.add(subscription);
|
2180 | });
|
2181 | });
|
2182 | };
|
2183 |
|
2184 | QueryManager.prototype.getQuery = function (queryId) {
|
2185 | return this.queries.get(queryId) || {
|
2186 | listeners: new Set(),
|
2187 | invalidated: false,
|
2188 | document: null,
|
2189 | newData: null,
|
2190 | lastRequestId: 1,
|
2191 | observableQuery: null,
|
2192 | subscriptions: new Set()
|
2193 | };
|
2194 | };
|
2195 |
|
2196 | QueryManager.prototype.setQuery = function (queryId, updater) {
|
2197 | var prev = this.getQuery(queryId);
|
2198 | var newInfo = (0, _tslib.__assign)((0, _tslib.__assign)({}, prev), updater(prev));
|
2199 | this.queries.set(queryId, newInfo);
|
2200 | };
|
2201 |
|
2202 | QueryManager.prototype.invalidate = function (queryId, invalidated) {
|
2203 | if (invalidated === void 0) {
|
2204 | invalidated = true;
|
2205 | }
|
2206 |
|
2207 | if (queryId) {
|
2208 | this.setQuery(queryId, function () {
|
2209 | return {
|
2210 | invalidated: invalidated
|
2211 | };
|
2212 | });
|
2213 | }
|
2214 | };
|
2215 |
|
2216 | QueryManager.prototype.prepareContext = function (context) {
|
2217 | if (context === void 0) {
|
2218 | context = {};
|
2219 | }
|
2220 |
|
2221 | var newContext = this.localState.prepareContext(context);
|
2222 | return (0, _tslib.__assign)((0, _tslib.__assign)({}, newContext), {
|
2223 | clientAwareness: this.clientAwareness
|
2224 | });
|
2225 | };
|
2226 |
|
2227 | QueryManager.prototype.checkInFlight = function (queryId) {
|
2228 | var query = this.queryStore.get(queryId);
|
2229 | return query && query.networkStatus !== NetworkStatus.ready && query.networkStatus !== NetworkStatus.error;
|
2230 | };
|
2231 |
|
2232 | QueryManager.prototype.startPollingQuery = function (options, queryId, listener) {
|
2233 | var _this = this;
|
2234 |
|
2235 | var pollInterval = options.pollInterval;
|
2236 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(pollInterval, 18) : (0, _tsInvariant.invariant)(pollInterval, 'Attempted to start a polling query without a polling interval.');
|
2237 |
|
2238 | if (!this.ssrMode) {
|
2239 | var info = this.pollingInfoByQueryId.get(queryId);
|
2240 |
|
2241 | if (!info) {
|
2242 | this.pollingInfoByQueryId.set(queryId, info = {});
|
2243 | }
|
2244 |
|
2245 | info.interval = pollInterval;
|
2246 | info.options = (0, _tslib.__assign)((0, _tslib.__assign)({}, options), {
|
2247 | fetchPolicy: 'network-only'
|
2248 | });
|
2249 |
|
2250 | var maybeFetch_1 = function () {
|
2251 | var info = _this.pollingInfoByQueryId.get(queryId);
|
2252 |
|
2253 | if (info) {
|
2254 | if (_this.checkInFlight(queryId)) {
|
2255 | poll_1();
|
2256 | } else {
|
2257 | _this.fetchQuery(queryId, info.options, FetchType.poll).then(poll_1, poll_1);
|
2258 | }
|
2259 | }
|
2260 | };
|
2261 |
|
2262 | var poll_1 = function () {
|
2263 | var info = _this.pollingInfoByQueryId.get(queryId);
|
2264 |
|
2265 | if (info) {
|
2266 | clearTimeout(info.timeout);
|
2267 | info.timeout = setTimeout(maybeFetch_1, info.interval);
|
2268 | }
|
2269 | };
|
2270 |
|
2271 | if (listener) {
|
2272 | this.addQueryListener(queryId, listener);
|
2273 | }
|
2274 |
|
2275 | poll_1();
|
2276 | }
|
2277 |
|
2278 | return queryId;
|
2279 | };
|
2280 |
|
2281 | QueryManager.prototype.stopPollingQuery = function (queryId) {
|
2282 | this.pollingInfoByQueryId.delete(queryId);
|
2283 | };
|
2284 |
|
2285 | return QueryManager;
|
2286 | }();
|
2287 |
|
2288 | var DataStore = function () {
|
2289 | function DataStore(initialCache) {
|
2290 | this.cache = initialCache;
|
2291 | }
|
2292 |
|
2293 | DataStore.prototype.getCache = function () {
|
2294 | return this.cache;
|
2295 | };
|
2296 |
|
2297 | DataStore.prototype.markQueryResult = function (result, document, variables, fetchMoreForQueryId, ignoreErrors) {
|
2298 | if (ignoreErrors === void 0) {
|
2299 | ignoreErrors = false;
|
2300 | }
|
2301 |
|
2302 | var writeWithErrors = !(0, _apolloUtilities.graphQLResultHasError)(result);
|
2303 |
|
2304 | if (ignoreErrors && (0, _apolloUtilities.graphQLResultHasError)(result) && result.data) {
|
2305 | writeWithErrors = true;
|
2306 | }
|
2307 |
|
2308 | if (!fetchMoreForQueryId && writeWithErrors) {
|
2309 | this.cache.write({
|
2310 | result: result.data,
|
2311 | dataId: 'ROOT_QUERY',
|
2312 | query: document,
|
2313 | variables: variables
|
2314 | });
|
2315 | }
|
2316 | };
|
2317 |
|
2318 | DataStore.prototype.markSubscriptionResult = function (result, document, variables) {
|
2319 | if (!(0, _apolloUtilities.graphQLResultHasError)(result)) {
|
2320 | this.cache.write({
|
2321 | result: result.data,
|
2322 | dataId: 'ROOT_SUBSCRIPTION',
|
2323 | query: document,
|
2324 | variables: variables
|
2325 | });
|
2326 | }
|
2327 | };
|
2328 |
|
2329 | DataStore.prototype.markMutationInit = function (mutation) {
|
2330 | var _this = this;
|
2331 |
|
2332 | if (mutation.optimisticResponse) {
|
2333 | var optimistic_1;
|
2334 |
|
2335 | if (typeof mutation.optimisticResponse === 'function') {
|
2336 | optimistic_1 = mutation.optimisticResponse(mutation.variables);
|
2337 | } else {
|
2338 | optimistic_1 = mutation.optimisticResponse;
|
2339 | }
|
2340 |
|
2341 | this.cache.recordOptimisticTransaction(function (c) {
|
2342 | var orig = _this.cache;
|
2343 | _this.cache = c;
|
2344 |
|
2345 | try {
|
2346 | _this.markMutationResult({
|
2347 | mutationId: mutation.mutationId,
|
2348 | result: {
|
2349 | data: optimistic_1
|
2350 | },
|
2351 | document: mutation.document,
|
2352 | variables: mutation.variables,
|
2353 | updateQueries: mutation.updateQueries,
|
2354 | update: mutation.update
|
2355 | });
|
2356 | } finally {
|
2357 | _this.cache = orig;
|
2358 | }
|
2359 | }, mutation.mutationId);
|
2360 | }
|
2361 | };
|
2362 |
|
2363 | DataStore.prototype.markMutationResult = function (mutation) {
|
2364 | var _this = this;
|
2365 |
|
2366 | if (!(0, _apolloUtilities.graphQLResultHasError)(mutation.result)) {
|
2367 | var cacheWrites_1 = [{
|
2368 | result: mutation.result.data,
|
2369 | dataId: 'ROOT_MUTATION',
|
2370 | query: mutation.document,
|
2371 | variables: mutation.variables
|
2372 | }];
|
2373 | var updateQueries_1 = mutation.updateQueries;
|
2374 |
|
2375 | if (updateQueries_1) {
|
2376 | Object.keys(updateQueries_1).forEach(function (id) {
|
2377 | var _a = updateQueries_1[id],
|
2378 | query = _a.query,
|
2379 | updater = _a.updater;
|
2380 |
|
2381 | var _b = _this.cache.diff({
|
2382 | query: query.document,
|
2383 | variables: query.variables,
|
2384 | returnPartialData: true,
|
2385 | optimistic: false
|
2386 | }),
|
2387 | currentQueryResult = _b.result,
|
2388 | complete = _b.complete;
|
2389 |
|
2390 | if (complete) {
|
2391 | var nextQueryResult = (0, _apolloUtilities.tryFunctionOrLogError)(function () {
|
2392 | return updater(currentQueryResult, {
|
2393 | mutationResult: mutation.result,
|
2394 | queryName: (0, _apolloUtilities.getOperationName)(query.document) || undefined,
|
2395 | queryVariables: query.variables
|
2396 | });
|
2397 | });
|
2398 |
|
2399 | if (nextQueryResult) {
|
2400 | cacheWrites_1.push({
|
2401 | result: nextQueryResult,
|
2402 | dataId: 'ROOT_QUERY',
|
2403 | query: query.document,
|
2404 | variables: query.variables
|
2405 | });
|
2406 | }
|
2407 | }
|
2408 | });
|
2409 | }
|
2410 |
|
2411 | this.cache.performTransaction(function (c) {
|
2412 | cacheWrites_1.forEach(function (write) {
|
2413 | return c.write(write);
|
2414 | });
|
2415 | var update = mutation.update;
|
2416 |
|
2417 | if (update) {
|
2418 | (0, _apolloUtilities.tryFunctionOrLogError)(function () {
|
2419 | return update(c, mutation.result);
|
2420 | });
|
2421 | }
|
2422 | });
|
2423 | }
|
2424 | };
|
2425 |
|
2426 | DataStore.prototype.markMutationComplete = function (_a) {
|
2427 | var mutationId = _a.mutationId,
|
2428 | optimisticResponse = _a.optimisticResponse;
|
2429 |
|
2430 | if (optimisticResponse) {
|
2431 | this.cache.removeOptimistic(mutationId);
|
2432 | }
|
2433 | };
|
2434 |
|
2435 | DataStore.prototype.markUpdateQueryResult = function (document, variables, newResult) {
|
2436 | this.cache.write({
|
2437 | result: newResult,
|
2438 | dataId: 'ROOT_QUERY',
|
2439 | variables: variables,
|
2440 | query: document
|
2441 | });
|
2442 | };
|
2443 |
|
2444 | DataStore.prototype.reset = function () {
|
2445 | return this.cache.reset();
|
2446 | };
|
2447 |
|
2448 | return DataStore;
|
2449 | }();
|
2450 |
|
2451 | var version = "2.6.10";
|
2452 | var hasSuggestedDevtools = false;
|
2453 |
|
2454 | var ApolloClient = function () {
|
2455 | function ApolloClient(options) {
|
2456 | var _this = this;
|
2457 |
|
2458 | this.defaultOptions = {};
|
2459 | this.resetStoreCallbacks = [];
|
2460 | this.clearStoreCallbacks = [];
|
2461 | var cache = options.cache,
|
2462 | _a = options.ssrMode,
|
2463 | ssrMode = _a === void 0 ? false : _a,
|
2464 | _b = options.ssrForceFetchDelay,
|
2465 | ssrForceFetchDelay = _b === void 0 ? 0 : _b,
|
2466 | connectToDevTools = options.connectToDevTools,
|
2467 | _c = options.queryDeduplication,
|
2468 | queryDeduplication = _c === void 0 ? true : _c,
|
2469 | defaultOptions = options.defaultOptions,
|
2470 | _d = options.assumeImmutableResults,
|
2471 | assumeImmutableResults = _d === void 0 ? false : _d,
|
2472 | resolvers = options.resolvers,
|
2473 | typeDefs = options.typeDefs,
|
2474 | fragmentMatcher = options.fragmentMatcher,
|
2475 | clientAwarenessName = options.name,
|
2476 | clientAwarenessVersion = options.version;
|
2477 | var link = options.link;
|
2478 |
|
2479 | if (!link && resolvers) {
|
2480 | link = _apolloLink.ApolloLink.empty();
|
2481 | }
|
2482 |
|
2483 | if (!link || !cache) {
|
2484 | throw process.env.NODE_ENV === "production" ? new _tsInvariant.InvariantError(4) : new _tsInvariant.InvariantError("In order to initialize Apollo Client, you must specify 'link' and 'cache' properties in the options object.\n" + "These options are part of the upgrade requirements when migrating from Apollo Client 1.x to Apollo Client 2.x.\n" + "For more information, please visit: https://www.apollographql.com/docs/tutorial/client.html#apollo-client-setup");
|
2485 | }
|
2486 |
|
2487 | this.link = link;
|
2488 | this.cache = cache;
|
2489 | this.store = new DataStore(cache);
|
2490 | this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
|
2491 | this.queryDeduplication = queryDeduplication;
|
2492 | this.defaultOptions = defaultOptions || {};
|
2493 | this.typeDefs = typeDefs;
|
2494 |
|
2495 | if (ssrForceFetchDelay) {
|
2496 | setTimeout(function () {
|
2497 | return _this.disableNetworkFetches = false;
|
2498 | }, ssrForceFetchDelay);
|
2499 | }
|
2500 |
|
2501 | this.watchQuery = this.watchQuery.bind(this);
|
2502 | this.query = this.query.bind(this);
|
2503 | this.mutate = this.mutate.bind(this);
|
2504 | this.resetStore = this.resetStore.bind(this);
|
2505 | this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);
|
2506 | var defaultConnectToDevTools = process.env.NODE_ENV !== 'production' && typeof window !== 'undefined' && !window.__APOLLO_CLIENT__;
|
2507 |
|
2508 | if (typeof connectToDevTools === 'undefined' ? defaultConnectToDevTools : connectToDevTools && typeof window !== 'undefined') {
|
2509 | window.__APOLLO_CLIENT__ = this;
|
2510 | }
|
2511 |
|
2512 | if (!hasSuggestedDevtools && process.env.NODE_ENV !== 'production') {
|
2513 | hasSuggestedDevtools = true;
|
2514 |
|
2515 | if (typeof window !== 'undefined' && window.document && window.top === window.self) {
|
2516 | if (typeof window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
|
2517 | if (window.navigator && window.navigator.userAgent && window.navigator.userAgent.indexOf('Chrome') > -1) {
|
2518 | console.debug('Download the Apollo DevTools ' + 'for a better development experience: ' + 'https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm');
|
2519 | }
|
2520 | }
|
2521 | }
|
2522 | }
|
2523 |
|
2524 | this.version = version;
|
2525 | this.localState = new LocalState({
|
2526 | cache: cache,
|
2527 | client: this,
|
2528 | resolvers: resolvers,
|
2529 | fragmentMatcher: fragmentMatcher
|
2530 | });
|
2531 | this.queryManager = new QueryManager({
|
2532 | link: this.link,
|
2533 | store: this.store,
|
2534 | queryDeduplication: queryDeduplication,
|
2535 | ssrMode: ssrMode,
|
2536 | clientAwareness: {
|
2537 | name: clientAwarenessName,
|
2538 | version: clientAwarenessVersion
|
2539 | },
|
2540 | localState: this.localState,
|
2541 | assumeImmutableResults: assumeImmutableResults,
|
2542 | onBroadcast: function () {
|
2543 | if (_this.devToolsHookCb) {
|
2544 | _this.devToolsHookCb({
|
2545 | action: {},
|
2546 | state: {
|
2547 | queries: _this.queryManager.queryStore.getStore(),
|
2548 | mutations: _this.queryManager.mutationStore.getStore()
|
2549 | },
|
2550 | dataWithOptimisticResults: _this.cache.extract(true)
|
2551 | });
|
2552 | }
|
2553 | }
|
2554 | });
|
2555 | }
|
2556 |
|
2557 | ApolloClient.prototype.stop = function () {
|
2558 | this.queryManager.stop();
|
2559 | };
|
2560 |
|
2561 | ApolloClient.prototype.watchQuery = function (options) {
|
2562 | if (this.defaultOptions.watchQuery) {
|
2563 | options = (0, _tslib.__assign)((0, _tslib.__assign)({}, this.defaultOptions.watchQuery), options);
|
2564 | }
|
2565 |
|
2566 | if (this.disableNetworkFetches && (options.fetchPolicy === 'network-only' || options.fetchPolicy === 'cache-and-network')) {
|
2567 | options = (0, _tslib.__assign)((0, _tslib.__assign)({}, options), {
|
2568 | fetchPolicy: 'cache-first'
|
2569 | });
|
2570 | }
|
2571 |
|
2572 | return this.queryManager.watchQuery(options);
|
2573 | };
|
2574 |
|
2575 | ApolloClient.prototype.query = function (options) {
|
2576 | if (this.defaultOptions.query) {
|
2577 | options = (0, _tslib.__assign)((0, _tslib.__assign)({}, this.defaultOptions.query), options);
|
2578 | }
|
2579 |
|
2580 | process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(options.fetchPolicy !== 'cache-and-network', 5) : (0, _tsInvariant.invariant)(options.fetchPolicy !== 'cache-and-network', 'The cache-and-network fetchPolicy does not work with client.query, because ' + 'client.query can only return a single result. Please use client.watchQuery ' + 'to receive multiple results from the cache and the network, or consider ' + 'using a different fetchPolicy, such as cache-first or network-only.');
|
2581 |
|
2582 | if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {
|
2583 | options = (0, _tslib.__assign)((0, _tslib.__assign)({}, options), {
|
2584 | fetchPolicy: 'cache-first'
|
2585 | });
|
2586 | }
|
2587 |
|
2588 | return this.queryManager.query(options);
|
2589 | };
|
2590 |
|
2591 | ApolloClient.prototype.mutate = function (options) {
|
2592 | if (this.defaultOptions.mutate) {
|
2593 | options = (0, _tslib.__assign)((0, _tslib.__assign)({}, this.defaultOptions.mutate), options);
|
2594 | }
|
2595 |
|
2596 | return this.queryManager.mutate(options);
|
2597 | };
|
2598 |
|
2599 | ApolloClient.prototype.subscribe = function (options) {
|
2600 | return this.queryManager.startGraphQLSubscription(options);
|
2601 | };
|
2602 |
|
2603 | ApolloClient.prototype.readQuery = function (options, optimistic) {
|
2604 | if (optimistic === void 0) {
|
2605 | optimistic = false;
|
2606 | }
|
2607 |
|
2608 | return this.cache.readQuery(options, optimistic);
|
2609 | };
|
2610 |
|
2611 | ApolloClient.prototype.readFragment = function (options, optimistic) {
|
2612 | if (optimistic === void 0) {
|
2613 | optimistic = false;
|
2614 | }
|
2615 |
|
2616 | return this.cache.readFragment(options, optimistic);
|
2617 | };
|
2618 |
|
2619 | ApolloClient.prototype.writeQuery = function (options) {
|
2620 | var result = this.cache.writeQuery(options);
|
2621 | this.queryManager.broadcastQueries();
|
2622 | return result;
|
2623 | };
|
2624 |
|
2625 | ApolloClient.prototype.writeFragment = function (options) {
|
2626 | var result = this.cache.writeFragment(options);
|
2627 | this.queryManager.broadcastQueries();
|
2628 | return result;
|
2629 | };
|
2630 |
|
2631 | ApolloClient.prototype.writeData = function (options) {
|
2632 | var result = this.cache.writeData(options);
|
2633 | this.queryManager.broadcastQueries();
|
2634 | return result;
|
2635 | };
|
2636 |
|
2637 | ApolloClient.prototype.__actionHookForDevTools = function (cb) {
|
2638 | this.devToolsHookCb = cb;
|
2639 | };
|
2640 |
|
2641 | ApolloClient.prototype.__requestRaw = function (payload) {
|
2642 | return (0, _apolloLink.execute)(this.link, payload);
|
2643 | };
|
2644 |
|
2645 | ApolloClient.prototype.initQueryManager = function () {
|
2646 | process.env.NODE_ENV === "production" || _tsInvariant.invariant.warn('Calling the initQueryManager method is no longer necessary, ' + 'and it will be removed from ApolloClient in version 3.0.');
|
2647 | return this.queryManager;
|
2648 | };
|
2649 |
|
2650 | ApolloClient.prototype.resetStore = function () {
|
2651 | var _this = this;
|
2652 |
|
2653 | return Promise.resolve().then(function () {
|
2654 | return _this.queryManager.clearStore();
|
2655 | }).then(function () {
|
2656 | return Promise.all(_this.resetStoreCallbacks.map(function (fn) {
|
2657 | return fn();
|
2658 | }));
|
2659 | }).then(function () {
|
2660 | return _this.reFetchObservableQueries();
|
2661 | });
|
2662 | };
|
2663 |
|
2664 | ApolloClient.prototype.clearStore = function () {
|
2665 | var _this = this;
|
2666 |
|
2667 | return Promise.resolve().then(function () {
|
2668 | return _this.queryManager.clearStore();
|
2669 | }).then(function () {
|
2670 | return Promise.all(_this.clearStoreCallbacks.map(function (fn) {
|
2671 | return fn();
|
2672 | }));
|
2673 | });
|
2674 | };
|
2675 |
|
2676 | ApolloClient.prototype.onResetStore = function (cb) {
|
2677 | var _this = this;
|
2678 |
|
2679 | this.resetStoreCallbacks.push(cb);
|
2680 | return function () {
|
2681 | _this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) {
|
2682 | return c !== cb;
|
2683 | });
|
2684 | };
|
2685 | };
|
2686 |
|
2687 | ApolloClient.prototype.onClearStore = function (cb) {
|
2688 | var _this = this;
|
2689 |
|
2690 | this.clearStoreCallbacks.push(cb);
|
2691 | return function () {
|
2692 | _this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) {
|
2693 | return c !== cb;
|
2694 | });
|
2695 | };
|
2696 | };
|
2697 |
|
2698 | ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {
|
2699 | return this.queryManager.reFetchObservableQueries(includeStandby);
|
2700 | };
|
2701 |
|
2702 | ApolloClient.prototype.extract = function (optimistic) {
|
2703 | return this.cache.extract(optimistic);
|
2704 | };
|
2705 |
|
2706 | ApolloClient.prototype.restore = function (serializedState) {
|
2707 | return this.cache.restore(serializedState);
|
2708 | };
|
2709 |
|
2710 | ApolloClient.prototype.addResolvers = function (resolvers) {
|
2711 | this.localState.addResolvers(resolvers);
|
2712 | };
|
2713 |
|
2714 | ApolloClient.prototype.setResolvers = function (resolvers) {
|
2715 | this.localState.setResolvers(resolvers);
|
2716 | };
|
2717 |
|
2718 | ApolloClient.prototype.getResolvers = function () {
|
2719 | return this.localState.getResolvers();
|
2720 | };
|
2721 |
|
2722 | ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {
|
2723 | this.localState.setFragmentMatcher(fragmentMatcher);
|
2724 | };
|
2725 |
|
2726 | return ApolloClient;
|
2727 | }();
|
2728 |
|
2729 | _exports.ApolloClient = ApolloClient;
|
2730 | var _default = ApolloClient;
|
2731 |
|
2732 | _exports.default = _default;
|
2733 | });
|