-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
QueryManager.ts
1143 lines (984 loc) · 33.1 KB
/
QueryManager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { DocumentNode } from 'graphql';
import { invariant, InvariantError } from 'ts-invariant';
import { equal } from '@wry/equality';
import { ApolloLink, execute, FetchResult } from '../link/core';
import { Cache, ApolloCache } from '../cache';
import {
getDefaultValues,
getOperationDefinition,
getOperationName,
hasClientExports,
graphQLResultHasError,
removeConnectionDirectiveFromDocument,
canUseWeakMap,
ObservableSubscription,
Observable,
asyncMap,
isNonEmptyArray,
Concast,
ConcastSourcesIterable,
} from '../utilities';
import { ApolloError, isApolloError } from '../errors';
import { MutationStore } from './MutationStore';
import {
QueryOptions,
WatchQueryOptions,
SubscriptionOptions,
MutationOptions,
WatchQueryFetchPolicy,
ErrorPolicy,
} from './watchQueryOptions';
import { ObservableQuery } from './ObservableQuery';
import { NetworkStatus, isNetworkRequestInFlight } from './networkStatus';
import {
ApolloQueryResult,
OperationVariables,
MutationQueryReducer,
} from './types';
import { LocalState } from './LocalState';
import { QueryInfo, QueryStoreValue } from './QueryInfo';
const { hasOwnProperty } = Object.prototype;
type QueryWithUpdater = {
updater: MutationQueryReducer<Object>;
queryInfo: QueryInfo;
};
export class QueryManager<TStore> {
public cache: ApolloCache<TStore>;
public link: ApolloLink;
public mutationStore: MutationStore = new MutationStore();
public readonly assumeImmutableResults: boolean;
public readonly ssrMode: boolean;
private queryDeduplication: boolean;
private clientAwareness: Record<string, string> = {};
private localState: LocalState<TStore>;
private onBroadcast: () => void;
// All the queries that the QueryManager is currently managing (not
// including mutations and subscriptions).
private queries = new Map<string, QueryInfo>();
// Maps from queryId strings to Promise rejection functions for
// currently active queries and fetches.
private fetchCancelFns = new Map<string, (error: any) => any>();
constructor({
cache,
link,
queryDeduplication = false,
onBroadcast = () => undefined,
ssrMode = false,
clientAwareness = {},
localState,
assumeImmutableResults,
}: {
cache: ApolloCache<TStore>;
link: ApolloLink;
queryDeduplication?: boolean;
onBroadcast?: () => void;
ssrMode?: boolean;
clientAwareness?: Record<string, string>;
localState?: LocalState<TStore>;
assumeImmutableResults?: boolean;
}) {
this.cache = cache;
this.link = link;
this.queryDeduplication = queryDeduplication;
this.onBroadcast = onBroadcast;
this.clientAwareness = clientAwareness;
this.localState = localState || new LocalState({ cache });
this.ssrMode = ssrMode;
this.assumeImmutableResults = !!assumeImmutableResults;
}
/**
* Call this method to terminate any active query processes, making it safe
* to dispose of this QueryManager instance.
*/
public stop() {
this.queries.forEach((_info, queryId) => {
this.stopQueryNoBroadcast(queryId);
});
this.cancelPendingFetches(
new InvariantError('QueryManager stopped while query was in flight'),
);
}
private cancelPendingFetches(error: Error) {
this.fetchCancelFns.forEach(cancel => cancel(error));
this.fetchCancelFns.clear();
}
public async mutate<T>({
mutation,
variables,
optimisticResponse,
updateQueries: updateQueriesByName,
refetchQueries = [],
awaitRefetchQueries = false,
update: updateWithProxyFn,
errorPolicy = 'none',
fetchPolicy,
context = {},
}: MutationOptions): Promise<FetchResult<T>> {
invariant(
mutation,
'mutation option is required. You must specify your GraphQL document in the mutation option.',
);
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."
);
const mutationId = this.generateMutationId();
mutation = this.transform(mutation).document;
variables = this.getVariables(mutation, variables);
if (this.transform(mutation).hasClientExports) {
variables = await this.localState.addExportedVariables(mutation, variables, context);
}
// Create a map of update queries by id to the query instead of by name.
const generateUpdateQueriesInfo: () => {
[queryId: string]: QueryWithUpdater;
} = () => {
const ret: { [queryId: string]: QueryWithUpdater } = {};
if (updateQueriesByName) {
this.queries.forEach(({ observableQuery }, queryId) => {
if (observableQuery) {
const { queryName } = observableQuery;
if (
queryName &&
hasOwnProperty.call(updateQueriesByName, queryName)
) {
ret[queryId] = {
updater: updateQueriesByName[queryName],
queryInfo: this.queries.get(queryId)!,
};
}
}
});
}
return ret;
};
this.mutationStore.initMutation(
mutationId,
mutation,
variables,
);
if (optimisticResponse) {
const optimistic = typeof optimisticResponse === 'function'
? optimisticResponse(variables)
: optimisticResponse;
this.cache.recordOptimisticTransaction(cache => {
try {
markMutationResult({
mutationId: mutationId,
result: { data: optimistic },
document: mutation,
variables: variables,
queryUpdatersById: generateUpdateQueriesInfo(),
update: updateWithProxyFn,
}, cache);
} catch (error) {
invariant.error(error);
}
}, mutationId);
}
this.broadcastQueries();
const self = this;
return new Promise((resolve, reject) => {
let storeResult: FetchResult<T> | null;
let error: ApolloError;
self.getObservableFromLink(
mutation,
{
...context,
optimisticResponse,
},
variables,
false,
).subscribe({
next(result: FetchResult<T>) {
if (graphQLResultHasError(result) && errorPolicy === 'none') {
error = new ApolloError({
graphQLErrors: result.errors,
});
return;
}
self.mutationStore.markMutationResult(mutationId);
if (fetchPolicy !== 'no-cache') {
try {
markMutationResult({
mutationId,
result,
document: mutation,
variables,
queryUpdatersById: generateUpdateQueriesInfo(),
update: updateWithProxyFn,
}, self.cache);
} catch (e) {
error = new ApolloError({
networkError: e,
});
return;
}
}
storeResult = result;
},
error(err: Error) {
self.mutationStore.markMutationError(mutationId, err);
if (optimisticResponse) {
self.cache.removeOptimistic(mutationId);
}
self.broadcastQueries();
reject(
new ApolloError({
networkError: err,
}),
);
},
complete() {
if (error) {
self.mutationStore.markMutationError(mutationId, error);
}
if (optimisticResponse) {
self.cache.removeOptimistic(mutationId);
}
self.broadcastQueries();
if (error) {
reject(error);
return;
}
// allow for conditional refetches
// XXX do we want to make this the only API one day?
if (typeof refetchQueries === 'function') {
refetchQueries = refetchQueries(storeResult!);
}
const refetchQueryPromises: Promise<
ApolloQueryResult<any>[] | ApolloQueryResult<{}>
>[] = [];
if (isNonEmptyArray(refetchQueries)) {
refetchQueries.forEach(refetchQuery => {
if (typeof refetchQuery === 'string') {
self.queries.forEach(({ observableQuery }) => {
if (observableQuery &&
observableQuery.queryName === refetchQuery) {
refetchQueryPromises.push(observableQuery.refetch());
}
});
} else {
const queryOptions: QueryOptions = {
query: refetchQuery.query,
variables: refetchQuery.variables,
fetchPolicy: 'network-only',
};
if (refetchQuery.context) {
queryOptions.context = refetchQuery.context;
}
refetchQueryPromises.push(self.query(queryOptions));
}
});
}
Promise.all(
awaitRefetchQueries ? refetchQueryPromises : [],
).then(() => {
if (
errorPolicy === 'ignore' &&
storeResult &&
graphQLResultHasError(storeResult)
) {
delete storeResult.errors;
}
resolve(storeResult!);
}, reject);
},
});
});
}
public fetchQuery<TData, TVars>(
queryId: string,
options: WatchQueryOptions<TVars>,
networkStatus?: NetworkStatus,
): Promise<ApolloQueryResult<TData>> {
return this.fetchQueryObservable<TData, TVars>(
queryId,
options,
networkStatus,
).promise;
}
public getQueryStore() {
const store: Record<string, QueryStoreValue> = Object.create(null);
this.queries.forEach((info, queryId) => {
store[queryId] = {
variables: info.variables,
networkStatus: info.networkStatus,
networkError: info.networkError,
graphQLErrors: info.graphQLErrors,
};
});
return store;
}
public resetErrors(queryId: string) {
const queryInfo = this.queries.get(queryId);
if (queryInfo) {
queryInfo.networkError = undefined;
queryInfo.graphQLErrors = [];
}
}
private transformCache = new (canUseWeakMap ? WeakMap : Map)<
DocumentNode,
Readonly<{
document: Readonly<DocumentNode>;
hasClientExports: boolean;
hasForcedResolvers: boolean;
clientQuery: Readonly<DocumentNode> | null;
serverQuery: Readonly<DocumentNode> | null;
defaultVars: Readonly<OperationVariables>;
}>
>();
public transform(document: DocumentNode) {
const { transformCache } = this;
if (!transformCache.has(document)) {
const transformed = this.cache.transformDocument(document);
const forLink = removeConnectionDirectiveFromDocument(
this.cache.transformForLink(transformed));
const clientQuery = this.localState.clientQuery(transformed);
const serverQuery = forLink && this.localState.serverQuery(forLink);
const cacheEntry = {
document: transformed,
// TODO These two calls (hasClientExports and shouldForceResolvers)
// could probably be merged into a single traversal.
hasClientExports: hasClientExports(transformed),
hasForcedResolvers: this.localState.shouldForceResolvers(transformed),
clientQuery,
serverQuery,
defaultVars: getDefaultValues(
getOperationDefinition(transformed)
) as OperationVariables,
};
const add = (doc: DocumentNode | null) => {
if (doc && !transformCache.has(doc)) {
transformCache.set(doc, cacheEntry);
}
}
// Add cacheEntry to the transformCache using several different keys,
// since any one of these documents could end up getting passed to the
// transform method again in the future.
add(document);
add(transformed);
add(clientQuery);
add(serverQuery);
}
return transformCache.get(document)!;
}
private getVariables(
document: DocumentNode,
variables?: OperationVariables,
): OperationVariables {
return {
...this.transform(document).defaultVars,
...variables,
};
}
public watchQuery<T, TVariables = OperationVariables>(
options: WatchQueryOptions<TVariables>,
): ObservableQuery<T, TVariables> {
// assign variable default values if supplied
options = {
...options,
variables: this.getVariables(
options.query,
options.variables,
) as TVariables,
};
if (typeof options.notifyOnNetworkStatusChange === 'undefined') {
options.notifyOnNetworkStatusChange = false;
}
const queryInfo = new QueryInfo(this.cache);
const observable = new ObservableQuery<T, TVariables>({
queryManager: this,
queryInfo,
options,
});
this.queries.set(observable.queryId, queryInfo);
queryInfo.init({
document: options.query,
observableQuery: observable,
variables: options.variables,
});
return observable;
}
public query<TData, TVars = OperationVariables>(
options: QueryOptions<TVars>,
): Promise<ApolloQueryResult<TData>> {
invariant(
options.query,
'query option is required. You must specify your GraphQL document ' +
'in the query option.',
);
invariant(
options.query.kind === 'Document',
'You must wrap the query string in a "gql" tag.',
);
invariant(
!(options as any).returnPartialData,
'returnPartialData option only supported on watchQuery.',
);
invariant(
!(options as any).pollInterval,
'pollInterval option only supported on watchQuery.',
);
const queryId = this.generateQueryId();
return this.fetchQuery<TData, TVars>(
queryId,
options,
).finally(() => this.stopQuery(queryId));
}
private queryIdCounter = 1;
public generateQueryId() {
return String(this.queryIdCounter++);
}
private requestIdCounter = 1;
public generateRequestId() {
return this.requestIdCounter++;
}
private mutationIdCounter = 1;
public generateMutationId() {
return String(this.mutationIdCounter++);
}
public stopQueryInStore(queryId: string) {
this.stopQueryInStoreNoBroadcast(queryId);
this.broadcastQueries();
}
private stopQueryInStoreNoBroadcast(queryId: string) {
const queryInfo = this.queries.get(queryId);
if (queryInfo) queryInfo.stop();
}
public clearStore(): Promise<void> {
// Before we have sent the reset action to the store, we can no longer
// rely on the results returned by in-flight requests since these may
// depend on values that previously existed in the data portion of the
// store. So, we cancel the promises and observers that we have issued
// so far and not yet resolved (in the case of queries).
this.cancelPendingFetches(new InvariantError(
'Store reset while query was in flight (not completed in link chain)',
));
this.queries.forEach(queryInfo => {
if (queryInfo.observableQuery) {
// Set loading to true so listeners don't trigger unless they want
// results with partial data.
queryInfo.networkStatus = NetworkStatus.loading;
} else {
queryInfo.stop();
}
});
this.mutationStore.reset();
// begin removing data from the store
return this.cache.reset();
}
public resetStore(): Promise<ApolloQueryResult<any>[]> {
// Similarly, we have to have to refetch each of the queries currently being
// observed. We refetch instead of error'ing on these since the assumption is that
// resetting the store doesn't eliminate the need for the queries currently being
// watched. If there is an existing query in flight when the store is reset,
// the promise for it will be rejected and its results will not be written to the
// store.
return this.clearStore().then(() => {
return this.reFetchObservableQueries();
});
}
public reFetchObservableQueries(
includeStandby: boolean = false,
): Promise<ApolloQueryResult<any>[]> {
const observableQueryPromises: Promise<ApolloQueryResult<any>>[] = [];
this.queries.forEach(({ observableQuery }, queryId) => {
if (observableQuery) {
const fetchPolicy = observableQuery.options.fetchPolicy;
observableQuery.resetLastResults();
if (
fetchPolicy !== 'cache-only' &&
(includeStandby || fetchPolicy !== 'standby')
) {
observableQueryPromises.push(observableQuery.refetch());
}
this.getQuery(queryId).setDiff(null);
}
});
this.broadcastQueries();
return Promise.all(observableQueryPromises);
}
public setObservableQuery(observableQuery: ObservableQuery<any, any>) {
this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);
}
public startGraphQLSubscription<T = any>({
query,
fetchPolicy,
variables,
context = {},
}: SubscriptionOptions): Observable<FetchResult<T>> {
query = this.transform(query).document;
variables = this.getVariables(query, variables);
const makeObservable = (variables: OperationVariables) =>
this.getObservableFromLink<T>(
query,
context,
variables,
false,
).map(result => {
if (!fetchPolicy || fetchPolicy !== 'no-cache') {
// the subscription interface should handle not sending us results we no longer subscribe to.
// XXX I don't think we ever send in an object with errors, but we might in the future...
if (!graphQLResultHasError(result)) {
this.cache.write({
query,
result: result.data,
dataId: 'ROOT_SUBSCRIPTION',
variables: variables,
});
}
this.broadcastQueries();
}
if (graphQLResultHasError(result)) {
throw new ApolloError({
graphQLErrors: result.errors,
});
}
return result;
});
if (this.transform(query).hasClientExports) {
const observablePromise = this.localState.addExportedVariables(
query,
variables,
context,
).then(makeObservable);
return new Observable<FetchResult<T>>(observer => {
let sub: ObservableSubscription | null = null;
observablePromise.then(
observable => sub = observable.subscribe(observer),
observer.error,
);
return () => sub && sub.unsubscribe();
});
}
return makeObservable(variables);
}
public stopQuery(queryId: string) {
this.stopQueryNoBroadcast(queryId);
this.broadcastQueries();
}
private stopQueryNoBroadcast(queryId: string) {
this.stopQueryInStoreNoBroadcast(queryId);
this.removeQuery(queryId);
}
public removeQuery(queryId: string) {
// teardown all links
// Both `QueryManager.fetchRequest` and `QueryManager.query` create separate promises
// that each add their reject functions to fetchCancelFns.
// A query created with `QueryManager.query()` could trigger a `QueryManager.fetchRequest`.
// The same queryId could have two rejection fns for two promises
this.fetchCancelFns.delete(queryId);
this.getQuery(queryId).subscriptions.forEach(x => x.unsubscribe());
this.queries.delete(queryId);
}
public broadcastQueries() {
this.onBroadcast();
this.queries.forEach(info => info.notify());
}
public getLocalState(): LocalState<TStore> {
return this.localState;
}
private inFlightLinkObservables = new Map<
DocumentNode,
Map<string, Observable<FetchResult>>
>();
private getObservableFromLink<T = any>(
query: DocumentNode,
context: any,
variables?: OperationVariables,
deduplication: boolean =
// Prefer context.queryDeduplication if specified.
context?.queryDeduplication ??
this.queryDeduplication,
): Observable<FetchResult<T>> {
let observable: Observable<FetchResult<T>>;
const { serverQuery } = this.transform(query);
if (serverQuery) {
const { inFlightLinkObservables, link } = this;
const operation = {
query: serverQuery,
variables,
operationName: getOperationName(serverQuery) || void 0,
context: this.prepareContext({
...context,
forceFetch: !deduplication
}),
};
context = operation.context;
if (deduplication) {
const byVariables = inFlightLinkObservables.get(serverQuery) || new Map();
inFlightLinkObservables.set(serverQuery, byVariables);
const varJson = JSON.stringify(variables);
observable = byVariables.get(varJson);
if (!observable) {
const concast = new Concast([
execute(link, operation) as Observable<FetchResult<T>>
]);
byVariables.set(varJson, observable = concast);
concast.cleanup(() => {
if (byVariables.delete(varJson) &&
byVariables.size < 1) {
inFlightLinkObservables.delete(serverQuery);
}
});
}
} else {
observable = new Concast([
execute(link, operation) as Observable<FetchResult<T>>
]);
}
} else {
observable = new Concast([
Observable.of({ data: {} } as FetchResult<T>)
]);
context = this.prepareContext(context);
}
const { clientQuery } = this.transform(query);
if (clientQuery) {
observable = asyncMap(observable, result => {
return this.localState.runResolvers({
document: clientQuery,
remoteResult: result,
context,
variables,
});
});
}
return observable;
}
private getResultsFromLink<TData, TVars>(
queryInfo: QueryInfo,
allowCacheWrite: boolean,
options: Pick<WatchQueryOptions<TVars>,
| "variables"
| "context"
| "fetchPolicy"
| "errorPolicy">,
): Observable<ApolloQueryResult<TData>> {
const { lastRequestId } = queryInfo;
return asyncMap(
this.getObservableFromLink(
queryInfo.document!,
options.context,
options.variables,
),
result => {
const hasErrors = isNonEmptyArray(result.errors);
if (lastRequestId >= queryInfo.lastRequestId) {
if (hasErrors && options.errorPolicy === "none") {
// Throwing here effectively calls observer.error.
throw queryInfo.markError(new ApolloError({
graphQLErrors: result.errors,
}));
}
queryInfo.markResult(result, options, allowCacheWrite);
queryInfo.markReady();
}
const aqr: ApolloQueryResult<TData> = {
data: result.data,
loading: false,
networkStatus: queryInfo.networkStatus || NetworkStatus.ready,
};
if (hasErrors && options.errorPolicy !== "ignore") {
aqr.errors = result.errors;
}
return aqr;
},
networkError => {
const error = isApolloError(networkError)
? networkError
: new ApolloError({ networkError });
if (lastRequestId >= queryInfo.lastRequestId) {
queryInfo.markError(error);
}
throw error;
},
);
}
public fetchQueryObservable<TData, TVars>(
queryId: string,
options: WatchQueryOptions<TVars>,
// The initial networkStatus for this fetch, most often
// NetworkStatus.loading, but also possibly fetchMore, poll, refetch,
// or setVariables.
networkStatus = NetworkStatus.loading,
): Concast<ApolloQueryResult<TData>> {
const query = this.transform(options.query).document;
const variables = this.getVariables(query, options.variables) as TVars;
const queryInfo = this.getQuery(queryId);
const oldNetworkStatus = queryInfo.networkStatus;
let {
fetchPolicy = "cache-first" as WatchQueryFetchPolicy,
errorPolicy = "none" as ErrorPolicy,
returnPartialData = false,
notifyOnNetworkStatusChange = false,
context = {},
} = options;
const mightUseNetwork =
fetchPolicy === "cache-first" ||
fetchPolicy === "cache-and-network" ||
fetchPolicy === "network-only" ||
fetchPolicy === "no-cache";
if (mightUseNetwork &&
notifyOnNetworkStatusChange &&
typeof oldNetworkStatus === "number" &&
oldNetworkStatus !== networkStatus &&
isNetworkRequestInFlight(networkStatus)) {
// In order to force delivery of an incomplete cache result with
// loading:true, we tweak the fetchPolicy to include the cache, and
// pretend that returnPartialData was enabled.
if (fetchPolicy !== "cache-first") {
fetchPolicy = "cache-and-network";
}
returnPartialData = true;
}
const normalized = Object.assign({}, options, {
query,
variables,
fetchPolicy,
errorPolicy,
returnPartialData,
notifyOnNetworkStatusChange,
context,
});
const fromVariables = (variables: TVars) => {
// Since normalized is always a fresh copy of options, it's safe to
// modify its properties here, rather than creating yet another new
// WatchQueryOptions object.
normalized.variables = variables;
return this.fetchQueryByPolicy<TData, TVars>(
queryInfo,
normalized,
networkStatus,
);
};
// This cancel function needs to be set before the concast is created,
// in case concast creation synchronously cancels the request.
this.fetchCancelFns.set(queryId, reason => {
// Delaying the cancellation using a Promise ensures that the
// concast variable has been initialized.
Promise.resolve().then(() => concast.cancel(reason));
});
// A Concast<T> can be created either from an Iterable<Observable<T>>
// or from a PromiseLike<Iterable<Observable<T>>>, where T in this
// case is ApolloQueryResult<TData>.
const concast = new Concast(
// If the query has @export(as: ...) directives, then we need to
// process those directives asynchronously. When there are no
// @export directives (the common case), we deliberately avoid
// wrapping the result of this.fetchQueryByPolicy in a Promise,
// since the timing of result delivery is (unfortunately) important
// for backwards compatibility. TODO This code could be simpler if
// we deprecated and removed LocalState.
this.transform(normalized.query).hasClientExports
? this.localState.addExportedVariables(
normalized.query,
normalized.variables,
normalized.context,
).then(fromVariables)
: fromVariables(normalized.variables!)
);
concast.cleanup(() => {
this.fetchCancelFns.delete(queryId);
if (options.nextFetchPolicy) {
// When someone chooses cache-and-network or network-only as their
// initial FetchPolicy, they often do not want future cache updates to
// trigger unconditional network requests, which is what repeatedly
// applying the cache-and-network or network-only policies would seem
// to imply. Instead, when the cache reports an update after the
// initial network request, it may be desirable for subsequent network
// requests to be triggered only if the cache result is incomplete.
// The options.nextFetchPolicy option provides an easy way to update
// options.fetchPolicy after the intial network request, without
// having to call observableQuery.setOptions.
options.fetchPolicy = options.nextFetchPolicy;
// The options.nextFetchPolicy transition should happen only once.
options.nextFetchPolicy = void 0;
}
});
return concast;
}
private fetchQueryByPolicy<TData, TVars>(
queryInfo: QueryInfo,
options: WatchQueryOptions<TVars>,
// The initial networkStatus for this fetch, most often
// NetworkStatus.loading, but also possibly fetchMore, poll, refetch,
// or setVariables.
networkStatus: NetworkStatus,
): ConcastSourcesIterable<ApolloQueryResult<TData>> {
const {
query,
variables,
fetchPolicy,
errorPolicy,
returnPartialData,
context,
} = options;
queryInfo.init({
document: query,
variables,
lastRequestId: this.generateRequestId(),
networkStatus,
});
const readCache = () => queryInfo.getDiff(variables);
const resultsFromCache = (
diff: Cache.DiffResult<TData>,
networkStatus = queryInfo.networkStatus || NetworkStatus.loading,
) => {
const data = diff.result as TData;
if (process.env.NODE_ENV !== 'production' &&
isNonEmptyArray(diff.missing) &&
!equal(data, {})) {
invariant.warn(`Missing cache result fields: ${
diff.missing.map(m => m.path.join('.')).join(', ')
}`, diff.missing);
}
const fromData = (data: TData) => Observable.of({
data,
loading: isNetworkRequestInFlight(networkStatus),
networkStatus,
...(diff.complete ? null : { partial: true }),
} as ApolloQueryResult<TData>);
if (this.transform(query).hasForcedResolvers) {
return this.localState.runResolvers({
document: query,
remoteResult: { data },
context,
variables,
onlyRunForcedResolvers: true,
}).then(resolved => fromData(resolved.data!));
}
return fromData(data);
};
const resultsFromLink = (allowCacheWrite: boolean) =>
this.getResultsFromLink<TData, TVars>(queryInfo, allowCacheWrite, {
variables,
context,
fetchPolicy,
errorPolicy,
});
switch (fetchPolicy) {