UNPKG

44.4 kBJavaScriptView Raw
1import { __assign, __awaiter, __generator } from "tslib";
2import { invariant, InvariantError } from "../utilities/globals/index.js";
3import { equal } from '@wry/equality';
4import { execute } from "../link/core/index.js";
5import { isExecutionPatchIncrementalResult, isExecutionPatchResult, } from "../utilities/common/incrementalResult.js";
6import { canonicalStringify } from "../cache/index.js";
7import { getDefaultValues, getOperationDefinition, getOperationName, hasClientExports, graphQLResultHasError, getGraphQLErrorsFromResult, removeConnectionDirectiveFromDocument, canUseWeakMap, Observable, asyncMap, isNonEmptyArray, Concast, makeUniqueId, isDocumentNode, isNonNullObject, } from "../utilities/index.js";
8import { mergeIncrementalData } from "../utilities/common/incrementalResult.js";
9import { ApolloError, isApolloError } from "../errors/index.js";
10import { ObservableQuery, logMissingFieldErrors } from "./ObservableQuery.js";
11import { NetworkStatus, isNetworkRequestInFlight } from "./networkStatus.js";
12import { LocalState } from "./LocalState.js";
13import { QueryInfo, shouldWriteResult, } from "./QueryInfo.js";
14var hasOwnProperty = Object.prototype.hasOwnProperty;
15var QueryManager = (function () {
16 function QueryManager(_a) {
17 var cache = _a.cache, link = _a.link, defaultOptions = _a.defaultOptions, _b = _a.queryDeduplication, queryDeduplication = _b === void 0 ? false : _b, onBroadcast = _a.onBroadcast, _c = _a.ssrMode, ssrMode = _c === void 0 ? false : _c, _d = _a.clientAwareness, clientAwareness = _d === void 0 ? {} : _d, localState = _a.localState, assumeImmutableResults = _a.assumeImmutableResults;
18 this.clientAwareness = {};
19 this.queries = new Map();
20 this.fetchCancelFns = new Map();
21 this.transformCache = new (canUseWeakMap ? WeakMap : Map)();
22 this.queryIdCounter = 1;
23 this.requestIdCounter = 1;
24 this.mutationIdCounter = 1;
25 this.inFlightLinkObservables = new Map();
26 this.cache = cache;
27 this.link = link;
28 this.defaultOptions = defaultOptions || Object.create(null);
29 this.queryDeduplication = queryDeduplication;
30 this.clientAwareness = clientAwareness;
31 this.localState = localState || new LocalState({ cache: cache });
32 this.ssrMode = ssrMode;
33 this.assumeImmutableResults = !!assumeImmutableResults;
34 if ((this.onBroadcast = onBroadcast)) {
35 this.mutationStore = Object.create(null);
36 }
37 }
38 QueryManager.prototype.stop = function () {
39 var _this = this;
40 this.queries.forEach(function (_info, queryId) {
41 _this.stopQueryNoBroadcast(queryId);
42 });
43 this.cancelPendingFetches(__DEV__ ? new InvariantError('QueryManager stopped while query was in flight') : new InvariantError(14));
44 };
45 QueryManager.prototype.cancelPendingFetches = function (error) {
46 this.fetchCancelFns.forEach(function (cancel) { return cancel(error); });
47 this.fetchCancelFns.clear();
48 };
49 QueryManager.prototype.mutate = function (_a) {
50 var _b, _c;
51 var mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, updateQueries = _a.updateQueries, _d = _a.refetchQueries, refetchQueries = _d === void 0 ? [] : _d, _e = _a.awaitRefetchQueries, awaitRefetchQueries = _e === void 0 ? false : _e, updateWithProxyFn = _a.update, onQueryUpdated = _a.onQueryUpdated, _f = _a.fetchPolicy, fetchPolicy = _f === void 0 ? ((_b = this.defaultOptions.mutate) === null || _b === void 0 ? void 0 : _b.fetchPolicy) || "network-only" : _f, _g = _a.errorPolicy, errorPolicy = _g === void 0 ? ((_c = this.defaultOptions.mutate) === null || _c === void 0 ? void 0 : _c.errorPolicy) || "none" : _g, keepRootFields = _a.keepRootFields, context = _a.context;
52 return __awaiter(this, void 0, void 0, function () {
53 var mutationId, _h, document, hasClientExports, mutationStoreValue, self;
54 return __generator(this, function (_j) {
55 switch (_j.label) {
56 case 0:
57 __DEV__ ? invariant(mutation, 'mutation option is required. You must specify your GraphQL document in the mutation option.') : invariant(mutation, 15);
58 __DEV__ ? invariant(fetchPolicy === 'network-only' ||
59 fetchPolicy === 'no-cache', "Mutations support only 'network-only' or 'no-cache' fetchPolicy strings. The default `network-only` behavior automatically writes mutation results to the cache. Passing `no-cache` skips the cache write.") : invariant(fetchPolicy === 'network-only' ||
60 fetchPolicy === 'no-cache', 16);
61 mutationId = this.generateMutationId();
62 _h = this.transform(mutation), document = _h.document, hasClientExports = _h.hasClientExports;
63 mutation = this.cache.transformForLink(document);
64 variables = this.getVariables(mutation, variables);
65 if (!hasClientExports) return [3, 2];
66 return [4, this.localState.addExportedVariables(mutation, variables, context)];
67 case 1:
68 variables = (_j.sent());
69 _j.label = 2;
70 case 2:
71 mutationStoreValue = this.mutationStore &&
72 (this.mutationStore[mutationId] = {
73 mutation: mutation,
74 variables: variables,
75 loading: true,
76 error: null,
77 });
78 if (optimisticResponse) {
79 this.markMutationOptimistic(optimisticResponse, {
80 mutationId: mutationId,
81 document: mutation,
82 variables: variables,
83 fetchPolicy: fetchPolicy,
84 errorPolicy: errorPolicy,
85 context: context,
86 updateQueries: updateQueries,
87 update: updateWithProxyFn,
88 keepRootFields: keepRootFields,
89 });
90 }
91 this.broadcastQueries();
92 self = this;
93 return [2, new Promise(function (resolve, reject) {
94 return asyncMap(self.getObservableFromLink(mutation, __assign(__assign({}, context), { optimisticResponse: optimisticResponse }), variables, false), function (result) {
95 if (graphQLResultHasError(result) && errorPolicy === 'none') {
96 throw new ApolloError({
97 graphQLErrors: getGraphQLErrorsFromResult(result),
98 });
99 }
100 if (mutationStoreValue) {
101 mutationStoreValue.loading = false;
102 mutationStoreValue.error = null;
103 }
104 var storeResult = __assign({}, result);
105 if (typeof refetchQueries === "function") {
106 refetchQueries = refetchQueries(storeResult);
107 }
108 if (errorPolicy === 'ignore' &&
109 graphQLResultHasError(storeResult)) {
110 delete storeResult.errors;
111 }
112 return self.markMutationResult({
113 mutationId: mutationId,
114 result: storeResult,
115 document: mutation,
116 variables: variables,
117 fetchPolicy: fetchPolicy,
118 errorPolicy: errorPolicy,
119 context: context,
120 update: updateWithProxyFn,
121 updateQueries: updateQueries,
122 awaitRefetchQueries: awaitRefetchQueries,
123 refetchQueries: refetchQueries,
124 removeOptimistic: optimisticResponse ? mutationId : void 0,
125 onQueryUpdated: onQueryUpdated,
126 keepRootFields: keepRootFields,
127 });
128 }).subscribe({
129 next: function (storeResult) {
130 self.broadcastQueries();
131 if (!('hasNext' in storeResult) || storeResult.hasNext === false) {
132 resolve(storeResult);
133 }
134 },
135 error: function (err) {
136 if (mutationStoreValue) {
137 mutationStoreValue.loading = false;
138 mutationStoreValue.error = err;
139 }
140 if (optimisticResponse) {
141 self.cache.removeOptimistic(mutationId);
142 }
143 self.broadcastQueries();
144 reject(err instanceof ApolloError ? err : new ApolloError({
145 networkError: err,
146 }));
147 },
148 });
149 })];
150 }
151 });
152 });
153 };
154 QueryManager.prototype.markMutationResult = function (mutation, cache) {
155 var _this = this;
156 if (cache === void 0) { cache = this.cache; }
157 var result = mutation.result;
158 var cacheWrites = [];
159 var skipCache = mutation.fetchPolicy === "no-cache";
160 if (!skipCache && shouldWriteResult(result, mutation.errorPolicy)) {
161 if (!isExecutionPatchIncrementalResult(result)) {
162 cacheWrites.push({
163 result: result.data,
164 dataId: 'ROOT_MUTATION',
165 query: mutation.document,
166 variables: mutation.variables,
167 });
168 }
169 if (isExecutionPatchIncrementalResult(result) && isNonEmptyArray(result.incremental)) {
170 var diff = cache.diff({
171 id: "ROOT_MUTATION",
172 query: this.transform(mutation.document).asQuery,
173 variables: mutation.variables,
174 optimistic: false,
175 returnPartialData: true,
176 });
177 var mergedData = void 0;
178 if (diff.result) {
179 mergedData = mergeIncrementalData(diff.result, result);
180 }
181 if (typeof mergedData !== 'undefined') {
182 result.data = mergedData;
183 cacheWrites.push({
184 result: mergedData,
185 dataId: 'ROOT_MUTATION',
186 query: mutation.document,
187 variables: mutation.variables,
188 });
189 }
190 }
191 var updateQueries_1 = mutation.updateQueries;
192 if (updateQueries_1) {
193 this.queries.forEach(function (_a, queryId) {
194 var observableQuery = _a.observableQuery;
195 var queryName = observableQuery && observableQuery.queryName;
196 if (!queryName || !hasOwnProperty.call(updateQueries_1, queryName)) {
197 return;
198 }
199 var updater = updateQueries_1[queryName];
200 var _b = _this.queries.get(queryId), document = _b.document, variables = _b.variables;
201 var _c = cache.diff({
202 query: document,
203 variables: variables,
204 returnPartialData: true,
205 optimistic: false,
206 }), currentQueryResult = _c.result, complete = _c.complete;
207 if (complete && currentQueryResult) {
208 var nextQueryResult = updater(currentQueryResult, {
209 mutationResult: result,
210 queryName: document && getOperationName(document) || void 0,
211 queryVariables: variables,
212 });
213 if (nextQueryResult) {
214 cacheWrites.push({
215 result: nextQueryResult,
216 dataId: 'ROOT_QUERY',
217 query: document,
218 variables: variables,
219 });
220 }
221 }
222 });
223 }
224 }
225 if (cacheWrites.length > 0 ||
226 mutation.refetchQueries ||
227 mutation.update ||
228 mutation.onQueryUpdated ||
229 mutation.removeOptimistic) {
230 var results_1 = [];
231 this.refetchQueries({
232 updateCache: function (cache) {
233 if (!skipCache) {
234 cacheWrites.forEach(function (write) { return cache.write(write); });
235 }
236 var update = mutation.update;
237 var isFinalResult = !isExecutionPatchResult(result) ||
238 (isExecutionPatchIncrementalResult(result) && !result.hasNext);
239 if (update) {
240 if (!skipCache) {
241 var diff = cache.diff({
242 id: "ROOT_MUTATION",
243 query: _this.transform(mutation.document).asQuery,
244 variables: mutation.variables,
245 optimistic: false,
246 returnPartialData: true,
247 });
248 if (diff.complete) {
249 result = __assign(__assign({}, result), { data: diff.result });
250 if ('incremental' in result) {
251 delete result.incremental;
252 }
253 if ('hasNext' in result) {
254 delete result.hasNext;
255 }
256 }
257 }
258 if (isFinalResult) {
259 update(cache, result, {
260 context: mutation.context,
261 variables: mutation.variables,
262 });
263 }
264 }
265 if (!skipCache && !mutation.keepRootFields && isFinalResult) {
266 cache.modify({
267 id: 'ROOT_MUTATION',
268 fields: function (value, _a) {
269 var fieldName = _a.fieldName, DELETE = _a.DELETE;
270 return fieldName === "__typename" ? value : DELETE;
271 },
272 });
273 }
274 },
275 include: mutation.refetchQueries,
276 optimistic: false,
277 removeOptimistic: mutation.removeOptimistic,
278 onQueryUpdated: mutation.onQueryUpdated || null,
279 }).forEach(function (result) { return results_1.push(result); });
280 if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {
281 return Promise.all(results_1).then(function () { return result; });
282 }
283 }
284 return Promise.resolve(result);
285 };
286 QueryManager.prototype.markMutationOptimistic = function (optimisticResponse, mutation) {
287 var _this = this;
288 var data = typeof optimisticResponse === "function"
289 ? optimisticResponse(mutation.variables)
290 : optimisticResponse;
291 return this.cache.recordOptimisticTransaction(function (cache) {
292 try {
293 _this.markMutationResult(__assign(__assign({}, mutation), { result: { data: data } }), cache);
294 }
295 catch (error) {
296 __DEV__ && invariant.error(error);
297 }
298 }, mutation.mutationId);
299 };
300 QueryManager.prototype.fetchQuery = function (queryId, options, networkStatus) {
301 return this.fetchQueryObservable(queryId, options, networkStatus).promise;
302 };
303 QueryManager.prototype.getQueryStore = function () {
304 var store = Object.create(null);
305 this.queries.forEach(function (info, queryId) {
306 store[queryId] = {
307 variables: info.variables,
308 networkStatus: info.networkStatus,
309 networkError: info.networkError,
310 graphQLErrors: info.graphQLErrors,
311 };
312 });
313 return store;
314 };
315 QueryManager.prototype.resetErrors = function (queryId) {
316 var queryInfo = this.queries.get(queryId);
317 if (queryInfo) {
318 queryInfo.networkError = undefined;
319 queryInfo.graphQLErrors = [];
320 }
321 };
322 QueryManager.prototype.transform = function (document) {
323 var transformCache = this.transformCache;
324 if (!transformCache.has(document)) {
325 var transformed = this.cache.transformDocument(document);
326 var noConnection = removeConnectionDirectiveFromDocument(transformed);
327 var clientQuery = this.localState.clientQuery(transformed);
328 var serverQuery = noConnection && this.localState.serverQuery(noConnection);
329 var cacheEntry_1 = {
330 document: transformed,
331 hasClientExports: hasClientExports(transformed),
332 hasForcedResolvers: this.localState.shouldForceResolvers(transformed),
333 clientQuery: clientQuery,
334 serverQuery: serverQuery,
335 defaultVars: getDefaultValues(getOperationDefinition(transformed)),
336 asQuery: __assign(__assign({}, transformed), { definitions: transformed.definitions.map(function (def) {
337 if (def.kind === "OperationDefinition" &&
338 def.operation !== "query") {
339 return __assign(__assign({}, def), { operation: "query" });
340 }
341 return def;
342 }) })
343 };
344 var add = function (doc) {
345 if (doc && !transformCache.has(doc)) {
346 transformCache.set(doc, cacheEntry_1);
347 }
348 };
349 add(document);
350 add(transformed);
351 add(clientQuery);
352 add(serverQuery);
353 }
354 return transformCache.get(document);
355 };
356 QueryManager.prototype.getVariables = function (document, variables) {
357 return __assign(__assign({}, this.transform(document).defaultVars), variables);
358 };
359 QueryManager.prototype.watchQuery = function (options) {
360 options = __assign(__assign({}, options), { variables: this.getVariables(options.query, options.variables) });
361 if (typeof options.notifyOnNetworkStatusChange === 'undefined') {
362 options.notifyOnNetworkStatusChange = false;
363 }
364 var queryInfo = new QueryInfo(this);
365 var observable = new ObservableQuery({
366 queryManager: this,
367 queryInfo: queryInfo,
368 options: options,
369 });
370 this.queries.set(observable.queryId, queryInfo);
371 queryInfo.init({
372 document: observable.query,
373 observableQuery: observable,
374 variables: observable.variables,
375 });
376 return observable;
377 };
378 QueryManager.prototype.query = function (options, queryId) {
379 var _this = this;
380 if (queryId === void 0) { queryId = this.generateQueryId(); }
381 __DEV__ ? invariant(options.query, 'query option is required. You must specify your GraphQL document ' +
382 'in the query option.') : invariant(options.query, 17);
383 __DEV__ ? invariant(options.query.kind === 'Document', 'You must wrap the query string in a "gql" tag.') : invariant(options.query.kind === 'Document', 18);
384 __DEV__ ? invariant(!options.returnPartialData, 'returnPartialData option only supported on watchQuery.') : invariant(!options.returnPartialData, 19);
385 __DEV__ ? invariant(!options.pollInterval, 'pollInterval option only supported on watchQuery.') : invariant(!options.pollInterval, 20);
386 return this.fetchQuery(queryId, options).finally(function () { return _this.stopQuery(queryId); });
387 };
388 QueryManager.prototype.generateQueryId = function () {
389 return String(this.queryIdCounter++);
390 };
391 QueryManager.prototype.generateRequestId = function () {
392 return this.requestIdCounter++;
393 };
394 QueryManager.prototype.generateMutationId = function () {
395 return String(this.mutationIdCounter++);
396 };
397 QueryManager.prototype.stopQueryInStore = function (queryId) {
398 this.stopQueryInStoreNoBroadcast(queryId);
399 this.broadcastQueries();
400 };
401 QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {
402 var queryInfo = this.queries.get(queryId);
403 if (queryInfo)
404 queryInfo.stop();
405 };
406 QueryManager.prototype.clearStore = function (options) {
407 if (options === void 0) { options = {
408 discardWatches: true,
409 }; }
410 this.cancelPendingFetches(__DEV__ ? new InvariantError('Store reset while query was in flight (not completed in link chain)') : new InvariantError(21));
411 this.queries.forEach(function (queryInfo) {
412 if (queryInfo.observableQuery) {
413 queryInfo.networkStatus = NetworkStatus.loading;
414 }
415 else {
416 queryInfo.stop();
417 }
418 });
419 if (this.mutationStore) {
420 this.mutationStore = Object.create(null);
421 }
422 return this.cache.reset(options);
423 };
424 QueryManager.prototype.getObservableQueries = function (include) {
425 var _this = this;
426 if (include === void 0) { include = "active"; }
427 var queries = new Map();
428 var queryNamesAndDocs = new Map();
429 var legacyQueryOptions = new Set();
430 if (Array.isArray(include)) {
431 include.forEach(function (desc) {
432 if (typeof desc === "string") {
433 queryNamesAndDocs.set(desc, false);
434 }
435 else if (isDocumentNode(desc)) {
436 queryNamesAndDocs.set(_this.transform(desc).document, false);
437 }
438 else if (isNonNullObject(desc) && desc.query) {
439 legacyQueryOptions.add(desc);
440 }
441 });
442 }
443 this.queries.forEach(function (_a, queryId) {
444 var oq = _a.observableQuery, document = _a.document;
445 if (oq) {
446 if (include === "all") {
447 queries.set(queryId, oq);
448 return;
449 }
450 var queryName = oq.queryName, fetchPolicy = oq.options.fetchPolicy;
451 if (fetchPolicy === "standby" ||
452 (include === "active" && !oq.hasObservers())) {
453 return;
454 }
455 if (include === "active" ||
456 (queryName && queryNamesAndDocs.has(queryName)) ||
457 (document && queryNamesAndDocs.has(document))) {
458 queries.set(queryId, oq);
459 if (queryName)
460 queryNamesAndDocs.set(queryName, true);
461 if (document)
462 queryNamesAndDocs.set(document, true);
463 }
464 }
465 });
466 if (legacyQueryOptions.size) {
467 legacyQueryOptions.forEach(function (options) {
468 var queryId = makeUniqueId("legacyOneTimeQuery");
469 var queryInfo = _this.getQuery(queryId).init({
470 document: options.query,
471 variables: options.variables,
472 });
473 var oq = new ObservableQuery({
474 queryManager: _this,
475 queryInfo: queryInfo,
476 options: __assign(__assign({}, options), { fetchPolicy: "network-only" }),
477 });
478 invariant(oq.queryId === queryId);
479 queryInfo.setObservableQuery(oq);
480 queries.set(queryId, oq);
481 });
482 }
483 if (__DEV__ && queryNamesAndDocs.size) {
484 queryNamesAndDocs.forEach(function (included, nameOrDoc) {
485 if (!included) {
486 __DEV__ && invariant.warn("Unknown query ".concat(typeof nameOrDoc === "string" ? "named " : "").concat(JSON.stringify(nameOrDoc, null, 2), " requested in refetchQueries options.include array"));
487 }
488 });
489 }
490 return queries;
491 };
492 QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {
493 var _this = this;
494 if (includeStandby === void 0) { includeStandby = false; }
495 var observableQueryPromises = [];
496 this.getObservableQueries(includeStandby ? "all" : "active").forEach(function (observableQuery, queryId) {
497 var fetchPolicy = observableQuery.options.fetchPolicy;
498 observableQuery.resetLastResults();
499 if (includeStandby ||
500 (fetchPolicy !== "standby" &&
501 fetchPolicy !== "cache-only")) {
502 observableQueryPromises.push(observableQuery.refetch());
503 }
504 _this.getQuery(queryId).setDiff(null);
505 });
506 this.broadcastQueries();
507 return Promise.all(observableQueryPromises);
508 };
509 QueryManager.prototype.setObservableQuery = function (observableQuery) {
510 this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);
511 };
512 QueryManager.prototype.startGraphQLSubscription = function (_a) {
513 var _this = this;
514 var query = _a.query, fetchPolicy = _a.fetchPolicy, errorPolicy = _a.errorPolicy, variables = _a.variables, _b = _a.context, context = _b === void 0 ? {} : _b;
515 query = this.transform(query).document;
516 variables = this.getVariables(query, variables);
517 var makeObservable = function (variables) {
518 return _this.getObservableFromLink(query, context, variables).map(function (result) {
519 if (fetchPolicy !== 'no-cache') {
520 if (shouldWriteResult(result, errorPolicy)) {
521 _this.cache.write({
522 query: query,
523 result: result.data,
524 dataId: 'ROOT_SUBSCRIPTION',
525 variables: variables,
526 });
527 }
528 _this.broadcastQueries();
529 }
530 if (graphQLResultHasError(result)) {
531 throw new ApolloError({
532 graphQLErrors: result.errors,
533 });
534 }
535 return result;
536 });
537 };
538 if (this.transform(query).hasClientExports) {
539 var observablePromise_1 = this.localState.addExportedVariables(query, variables, context).then(makeObservable);
540 return new Observable(function (observer) {
541 var sub = null;
542 observablePromise_1.then(function (observable) { return sub = observable.subscribe(observer); }, observer.error);
543 return function () { return sub && sub.unsubscribe(); };
544 });
545 }
546 return makeObservable(variables);
547 };
548 QueryManager.prototype.stopQuery = function (queryId) {
549 this.stopQueryNoBroadcast(queryId);
550 this.broadcastQueries();
551 };
552 QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {
553 this.stopQueryInStoreNoBroadcast(queryId);
554 this.removeQuery(queryId);
555 };
556 QueryManager.prototype.removeQuery = function (queryId) {
557 this.fetchCancelFns.delete(queryId);
558 if (this.queries.has(queryId)) {
559 this.getQuery(queryId).stop();
560 this.queries.delete(queryId);
561 }
562 };
563 QueryManager.prototype.broadcastQueries = function () {
564 if (this.onBroadcast)
565 this.onBroadcast();
566 this.queries.forEach(function (info) { return info.notify(); });
567 };
568 QueryManager.prototype.getLocalState = function () {
569 return this.localState;
570 };
571 QueryManager.prototype.getObservableFromLink = function (query, context, variables, deduplication) {
572 var _this = this;
573 var _a;
574 if (deduplication === void 0) { deduplication = (_a = context === null || context === void 0 ? void 0 : context.queryDeduplication) !== null && _a !== void 0 ? _a : this.queryDeduplication; }
575 var observable;
576 var serverQuery = this.transform(query).serverQuery;
577 if (serverQuery) {
578 var _b = this, inFlightLinkObservables_1 = _b.inFlightLinkObservables, link = _b.link;
579 var operation = {
580 query: serverQuery,
581 variables: variables,
582 operationName: getOperationName(serverQuery) || void 0,
583 context: this.prepareContext(__assign(__assign({}, context), { forceFetch: !deduplication })),
584 };
585 context = operation.context;
586 if (deduplication) {
587 var byVariables_1 = inFlightLinkObservables_1.get(serverQuery) || new Map();
588 inFlightLinkObservables_1.set(serverQuery, byVariables_1);
589 var varJson_1 = canonicalStringify(variables);
590 observable = byVariables_1.get(varJson_1);
591 if (!observable) {
592 var concast = new Concast([
593 execute(link, operation)
594 ]);
595 byVariables_1.set(varJson_1, observable = concast);
596 concast.beforeNext(function () {
597 if (byVariables_1.delete(varJson_1) &&
598 byVariables_1.size < 1) {
599 inFlightLinkObservables_1.delete(serverQuery);
600 }
601 });
602 }
603 }
604 else {
605 observable = new Concast([
606 execute(link, operation)
607 ]);
608 }
609 }
610 else {
611 observable = new Concast([
612 Observable.of({ data: {} })
613 ]);
614 context = this.prepareContext(context);
615 }
616 var clientQuery = this.transform(query).clientQuery;
617 if (clientQuery) {
618 observable = asyncMap(observable, function (result) {
619 return _this.localState.runResolvers({
620 document: clientQuery,
621 remoteResult: result,
622 context: context,
623 variables: variables,
624 });
625 });
626 }
627 return observable;
628 };
629 QueryManager.prototype.getResultsFromLink = function (queryInfo, cacheWriteBehavior, options) {
630 var requestId = queryInfo.lastRequestId = this.generateRequestId();
631 var linkDocument = this.cache.transformForLink(this.transform(queryInfo.document).document);
632 return asyncMap(this.getObservableFromLink(linkDocument, options.context, options.variables), function (result) {
633 var graphQLErrors = getGraphQLErrorsFromResult(result);
634 var hasErrors = graphQLErrors.length > 0;
635 if (requestId >= queryInfo.lastRequestId) {
636 if (hasErrors && options.errorPolicy === "none") {
637 throw queryInfo.markError(new ApolloError({
638 graphQLErrors: graphQLErrors,
639 }));
640 }
641 queryInfo.markResult(result, linkDocument, options, cacheWriteBehavior);
642 queryInfo.markReady();
643 }
644 var aqr = {
645 data: result.data,
646 loading: false,
647 networkStatus: NetworkStatus.ready,
648 };
649 if (hasErrors && options.errorPolicy !== "ignore") {
650 aqr.errors = graphQLErrors;
651 aqr.networkStatus = NetworkStatus.error;
652 }
653 return aqr;
654 }, function (networkError) {
655 var error = isApolloError(networkError)
656 ? networkError
657 : new ApolloError({ networkError: networkError });
658 if (requestId >= queryInfo.lastRequestId) {
659 queryInfo.markError(error);
660 }
661 throw error;
662 });
663 };
664 QueryManager.prototype.fetchQueryObservable = function (queryId, options, networkStatus) {
665 var _this = this;
666 if (networkStatus === void 0) { networkStatus = NetworkStatus.loading; }
667 var query = this.transform(options.query).document;
668 var variables = this.getVariables(query, options.variables);
669 var queryInfo = this.getQuery(queryId);
670 var defaults = this.defaultOptions.watchQuery;
671 var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? defaults && defaults.fetchPolicy || "cache-first" : _a, _b = options.errorPolicy, errorPolicy = _b === void 0 ? defaults && defaults.errorPolicy || "none" : _b, _c = options.returnPartialData, returnPartialData = _c === void 0 ? false : _c, _d = options.notifyOnNetworkStatusChange, notifyOnNetworkStatusChange = _d === void 0 ? false : _d, _e = options.context, context = _e === void 0 ? {} : _e;
672 var normalized = Object.assign({}, options, {
673 query: query,
674 variables: variables,
675 fetchPolicy: fetchPolicy,
676 errorPolicy: errorPolicy,
677 returnPartialData: returnPartialData,
678 notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,
679 context: context,
680 });
681 var fromVariables = function (variables) {
682 normalized.variables = variables;
683 var concastSources = _this.fetchQueryByPolicy(queryInfo, normalized, networkStatus);
684 if (normalized.fetchPolicy !== "standby" &&
685 concastSources.length > 0 &&
686 queryInfo.observableQuery) {
687 queryInfo.observableQuery["applyNextFetchPolicy"]("after-fetch", options);
688 }
689 return concastSources;
690 };
691 var cleanupCancelFn = function () { return _this.fetchCancelFns.delete(queryId); };
692 this.fetchCancelFns.set(queryId, function (reason) {
693 cleanupCancelFn();
694 setTimeout(function () { return concast.cancel(reason); });
695 });
696 var concast = new Concast(this.transform(normalized.query).hasClientExports
697 ? this.localState.addExportedVariables(normalized.query, normalized.variables, normalized.context).then(fromVariables)
698 : fromVariables(normalized.variables));
699 concast.promise.then(cleanupCancelFn, cleanupCancelFn);
700 return concast;
701 };
702 QueryManager.prototype.refetchQueries = function (_a) {
703 var _this = this;
704 var updateCache = _a.updateCache, include = _a.include, _b = _a.optimistic, optimistic = _b === void 0 ? false : _b, _c = _a.removeOptimistic, removeOptimistic = _c === void 0 ? optimistic ? makeUniqueId("refetchQueries") : void 0 : _c, onQueryUpdated = _a.onQueryUpdated;
705 var includedQueriesById = new Map();
706 if (include) {
707 this.getObservableQueries(include).forEach(function (oq, queryId) {
708 includedQueriesById.set(queryId, {
709 oq: oq,
710 lastDiff: _this.getQuery(queryId).getDiff(),
711 });
712 });
713 }
714 var results = new Map;
715 if (updateCache) {
716 this.cache.batch({
717 update: updateCache,
718 optimistic: optimistic && removeOptimistic || false,
719 removeOptimistic: removeOptimistic,
720 onWatchUpdated: function (watch, diff, lastDiff) {
721 var oq = watch.watcher instanceof QueryInfo &&
722 watch.watcher.observableQuery;
723 if (oq) {
724 if (onQueryUpdated) {
725 includedQueriesById.delete(oq.queryId);
726 var result = onQueryUpdated(oq, diff, lastDiff);
727 if (result === true) {
728 result = oq.refetch();
729 }
730 if (result !== false) {
731 results.set(oq, result);
732 }
733 return result;
734 }
735 if (onQueryUpdated !== null) {
736 includedQueriesById.set(oq.queryId, { oq: oq, lastDiff: lastDiff, diff: diff });
737 }
738 }
739 },
740 });
741 }
742 if (includedQueriesById.size) {
743 includedQueriesById.forEach(function (_a, queryId) {
744 var oq = _a.oq, lastDiff = _a.lastDiff, diff = _a.diff;
745 var result;
746 if (onQueryUpdated) {
747 if (!diff) {
748 var info = oq["queryInfo"];
749 info.reset();
750 diff = info.getDiff();
751 }
752 result = onQueryUpdated(oq, diff, lastDiff);
753 }
754 if (!onQueryUpdated || result === true) {
755 result = oq.refetch();
756 }
757 if (result !== false) {
758 results.set(oq, result);
759 }
760 if (queryId.indexOf("legacyOneTimeQuery") >= 0) {
761 _this.stopQueryNoBroadcast(queryId);
762 }
763 });
764 }
765 if (removeOptimistic) {
766 this.cache.removeOptimistic(removeOptimistic);
767 }
768 return results;
769 };
770 QueryManager.prototype.fetchQueryByPolicy = function (queryInfo, _a, networkStatus) {
771 var _this = this;
772 var query = _a.query, variables = _a.variables, fetchPolicy = _a.fetchPolicy, refetchWritePolicy = _a.refetchWritePolicy, errorPolicy = _a.errorPolicy, returnPartialData = _a.returnPartialData, context = _a.context, notifyOnNetworkStatusChange = _a.notifyOnNetworkStatusChange;
773 var oldNetworkStatus = queryInfo.networkStatus;
774 queryInfo.init({
775 document: this.transform(query).document,
776 variables: variables,
777 networkStatus: networkStatus,
778 });
779 var readCache = function () { return queryInfo.getDiff(variables); };
780 var resultsFromCache = function (diff, networkStatus) {
781 if (networkStatus === void 0) { networkStatus = queryInfo.networkStatus || NetworkStatus.loading; }
782 var data = diff.result;
783 if (__DEV__ &&
784 !returnPartialData &&
785 !equal(data, {})) {
786 logMissingFieldErrors(diff.missing);
787 }
788 var fromData = function (data) { return Observable.of(__assign({ data: data, loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus }, (diff.complete ? null : { partial: true }))); };
789 if (data && _this.transform(query).hasForcedResolvers) {
790 return _this.localState.runResolvers({
791 document: query,
792 remoteResult: { data: data },
793 context: context,
794 variables: variables,
795 onlyRunForcedResolvers: true,
796 }).then(function (resolved) { return fromData(resolved.data || void 0); });
797 }
798 if (errorPolicy === 'none' &&
799 networkStatus === NetworkStatus.refetch &&
800 Array.isArray(diff.missing)) {
801 return fromData(void 0);
802 }
803 return fromData(data);
804 };
805 var cacheWriteBehavior = fetchPolicy === "no-cache" ? 0 :
806 (networkStatus === NetworkStatus.refetch &&
807 refetchWritePolicy !== "merge") ? 1
808 : 2;
809 var resultsFromLink = function () { return _this.getResultsFromLink(queryInfo, cacheWriteBehavior, {
810 variables: variables,
811 context: context,
812 fetchPolicy: fetchPolicy,
813 errorPolicy: errorPolicy,
814 }); };
815 var shouldNotify = notifyOnNetworkStatusChange &&
816 typeof oldNetworkStatus === "number" &&
817 oldNetworkStatus !== networkStatus &&
818 isNetworkRequestInFlight(networkStatus);
819 switch (fetchPolicy) {
820 default:
821 case "cache-first": {
822 var diff = readCache();
823 if (diff.complete) {
824 return [
825 resultsFromCache(diff, queryInfo.markReady()),
826 ];
827 }
828 if (returnPartialData || shouldNotify) {
829 return [
830 resultsFromCache(diff),
831 resultsFromLink(),
832 ];
833 }
834 return [
835 resultsFromLink(),
836 ];
837 }
838 case "cache-and-network": {
839 var diff = readCache();
840 if (diff.complete || returnPartialData || shouldNotify) {
841 return [
842 resultsFromCache(diff),
843 resultsFromLink(),
844 ];
845 }
846 return [
847 resultsFromLink(),
848 ];
849 }
850 case "cache-only":
851 return [
852 resultsFromCache(readCache(), queryInfo.markReady()),
853 ];
854 case "network-only":
855 if (shouldNotify) {
856 return [
857 resultsFromCache(readCache()),
858 resultsFromLink(),
859 ];
860 }
861 return [resultsFromLink()];
862 case "no-cache":
863 if (shouldNotify) {
864 return [
865 resultsFromCache(queryInfo.getDiff()),
866 resultsFromLink(),
867 ];
868 }
869 return [resultsFromLink()];
870 case "standby":
871 return [];
872 }
873 };
874 QueryManager.prototype.getQuery = function (queryId) {
875 if (queryId && !this.queries.has(queryId)) {
876 this.queries.set(queryId, new QueryInfo(this, queryId));
877 }
878 return this.queries.get(queryId);
879 };
880 QueryManager.prototype.prepareContext = function (context) {
881 if (context === void 0) { context = {}; }
882 var newContext = this.localState.prepareContext(context);
883 return __assign(__assign({}, newContext), { clientAwareness: this.clientAwareness });
884 };
885 return QueryManager;
886}());
887export { QueryManager };
888//# sourceMappingURL=QueryManager.js.map
\No newline at end of file