UNPKG

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