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