-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
QueryManager.ts
1814 lines (1592 loc) · 57.9 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 { invariant, newInvariantError } from "../utilities/globals/index.js";
import type { DocumentNode } from "graphql";
// TODO(brian): A hack until this issue is resolved (https://github.com/graphql/graphql-js/issues/3356)
type OperationTypeNode = any;
import { equal } from "@wry/equality";
import type { ApolloLink, FetchResult } from "../link/core/index.js";
import { execute } from "../link/core/index.js";
import {
addNonReactiveToNamedFragments,
defaultCacheSizes,
hasDirectives,
isExecutionPatchIncrementalResult,
isExecutionPatchResult,
isFullyUnmaskedOperation,
removeDirectivesFromDocument,
} from "../utilities/index.js";
import type { Cache, ApolloCache } from "../cache/index.js";
import { canonicalStringify } from "../cache/index.js";
import type {
ObservableSubscription,
ConcastSourcesArray,
} from "../utilities/index.js";
import {
getDefaultValues,
getOperationDefinition,
getOperationName,
hasClientExports,
graphQLResultHasError,
getGraphQLErrorsFromResult,
Observable,
asyncMap,
isNonEmptyArray,
Concast,
makeUniqueId,
isDocumentNode,
isNonNullObject,
DocumentTransform,
} from "../utilities/index.js";
import { mergeIncrementalData } from "../utilities/common/incrementalResult.js";
import {
ApolloError,
isApolloError,
graphQLResultHasProtocolErrors,
} from "../errors/index.js";
import type {
QueryOptions,
WatchQueryOptions,
SubscriptionOptions,
MutationOptions,
ErrorPolicy,
MutationFetchPolicy,
WatchQueryFetchPolicy,
} from "./watchQueryOptions.js";
import { ObservableQuery, logMissingFieldErrors } from "./ObservableQuery.js";
import { NetworkStatus, isNetworkRequestInFlight } from "./networkStatus.js";
import type {
ApolloQueryResult,
OperationVariables,
MutationUpdaterFunction,
OnQueryUpdated,
InternalRefetchQueriesInclude,
InternalRefetchQueriesOptions,
InternalRefetchQueriesResult,
InternalRefetchQueriesMap,
DefaultContext,
} from "./types.js";
import type { LocalState } from "./LocalState.js";
import type { QueryStoreValue } from "./QueryInfo.js";
import {
QueryInfo,
shouldWriteResult,
CacheWriteBehavior,
} from "./QueryInfo.js";
import type { ApolloErrorOptions } from "../errors/index.js";
import { PROTOCOL_ERRORS_SYMBOL } from "../errors/index.js";
import { print } from "../utilities/index.js";
import type { IgnoreModifier } from "../cache/core/types/common.js";
import type { TODO } from "../utilities/types/TODO.js";
const { hasOwnProperty } = Object.prototype;
const IGNORE: IgnoreModifier = Object.create(null);
interface MutationStoreValue {
mutation: DocumentNode;
variables: Record<string, any>;
loading: boolean;
error: Error | null;
}
type UpdateQueries<TData> = MutationOptions<TData, any, any>["updateQueries"];
interface TransformCacheEntry {
hasClientExports: boolean;
hasForcedResolvers: boolean;
hasNonreactiveDirective: boolean;
nonReactiveQuery: DocumentNode;
clientQuery: DocumentNode | null;
serverQuery: DocumentNode | null;
defaultVars: OperationVariables;
asQuery: DocumentNode;
}
import type { DefaultOptions } from "./ApolloClient.js";
import { Trie } from "@wry/trie";
import { AutoCleanedWeakCache, cacheSizes } from "../utilities/index.js";
import { maskFragment, maskOperation } from "../masking/index.js";
import type { MaybeMasked, Unmasked } from "../masking/index.js";
interface MaskFragmentOptions<TData> {
fragment: DocumentNode;
data: TData;
fragmentName?: string;
}
interface MaskOperationOptions<TData> {
document: DocumentNode;
data: TData;
id: string;
fetchPolicy?: WatchQueryFetchPolicy;
}
export interface QueryManagerOptions<TStore> {
cache: ApolloCache<TStore>;
link: ApolloLink;
defaultOptions: DefaultOptions;
documentTransform: DocumentTransform | null | undefined;
queryDeduplication: boolean;
onBroadcast: undefined | (() => void);
ssrMode: boolean;
clientAwareness: Record<string, string>;
localState: LocalState<TStore>;
assumeImmutableResults: boolean;
defaultContext: Partial<DefaultContext> | undefined;
dataMasking: boolean;
}
export class QueryManager<TStore> {
public cache: ApolloCache<TStore>;
public link: ApolloLink;
public defaultOptions: DefaultOptions;
public readonly assumeImmutableResults: boolean;
public readonly documentTransform: DocumentTransform;
public readonly ssrMode: boolean;
public readonly defaultContext: Partial<DefaultContext>;
public readonly dataMasking: boolean;
private queryDeduplication: boolean;
private clientAwareness: Record<string, string> = {};
private localState: LocalState<TStore>;
private onBroadcast?: () => void;
public mutationStore?: {
[mutationId: string]: MutationStoreValue;
};
// 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.
// Use protected instead of private field so
// @apollo/experimental-nextjs-app-support can access type info.
protected fetchCancelFns = new Map<string, (error: any) => any>();
constructor(options: QueryManagerOptions<TStore>) {
const defaultDocumentTransform = new DocumentTransform(
(document) => this.cache.transformDocument(document),
// Allow the apollo cache to manage its own transform caches
{ cache: false }
);
this.cache = options.cache;
this.link = options.link;
this.defaultOptions = options.defaultOptions;
this.queryDeduplication = options.queryDeduplication;
this.clientAwareness = options.clientAwareness;
this.localState = options.localState;
this.ssrMode = options.ssrMode;
this.assumeImmutableResults = options.assumeImmutableResults;
this.dataMasking = options.dataMasking;
const documentTransform = options.documentTransform;
this.documentTransform =
documentTransform ?
defaultDocumentTransform
.concat(documentTransform)
// The custom document transform may add new fragment spreads or new
// field selections, so we want to give the cache a chance to run
// again. For example, the InMemoryCache adds __typename to field
// selections and fragments from the fragment registry.
.concat(defaultDocumentTransform)
: defaultDocumentTransform;
this.defaultContext = options.defaultContext || Object.create(null);
if ((this.onBroadcast = options.onBroadcast)) {
this.mutationStore = Object.create(null);
}
}
/**
* 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(
newInvariantError("QueryManager stopped while query was in flight")
);
}
private cancelPendingFetches(error: Error) {
this.fetchCancelFns.forEach((cancel) => cancel(error));
this.fetchCancelFns.clear();
}
public async mutate<
TData,
TVariables extends OperationVariables,
TContext extends Record<string, any>,
TCache extends ApolloCache<any>,
>({
mutation,
variables,
optimisticResponse,
updateQueries,
refetchQueries = [],
awaitRefetchQueries = false,
update: updateWithProxyFn,
onQueryUpdated,
fetchPolicy = this.defaultOptions.mutate?.fetchPolicy || "network-only",
errorPolicy = this.defaultOptions.mutate?.errorPolicy || "none",
keepRootFields,
context,
}: MutationOptions<TData, TVariables, TContext>): Promise<
FetchResult<MaybeMasked<TData>>
> {
invariant(
mutation,
"mutation option is required. You must specify your GraphQL document in the mutation option."
);
invariant(
fetchPolicy === "network-only" || 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."
);
const mutationId = this.generateMutationId();
mutation = this.cache.transformForLink(this.transform(mutation));
const { hasClientExports } = this.getDocumentInfo(mutation);
variables = this.getVariables(mutation, variables) as TVariables;
if (hasClientExports) {
variables = (await this.localState.addExportedVariables(
mutation,
variables,
context
)) as TVariables;
}
const mutationStoreValue =
this.mutationStore &&
(this.mutationStore[mutationId] = {
mutation,
variables,
loading: true,
error: null,
} as MutationStoreValue);
const isOptimistic =
optimisticResponse &&
this.markMutationOptimistic<TData, TVariables, TContext, TCache>(
optimisticResponse,
{
mutationId,
document: mutation,
variables,
fetchPolicy,
errorPolicy,
context,
updateQueries,
update: updateWithProxyFn,
keepRootFields,
}
);
this.broadcastQueries();
const self = this;
return new Promise((resolve, reject) => {
return asyncMap(
self.getObservableFromLink(
mutation,
{
...context,
optimisticResponse: isOptimistic ? optimisticResponse : void 0,
},
variables,
{},
false
),
(result: FetchResult<TData>) => {
if (graphQLResultHasError(result) && errorPolicy === "none") {
throw new ApolloError({
graphQLErrors: getGraphQLErrorsFromResult(result),
});
}
if (mutationStoreValue) {
mutationStoreValue.loading = false;
mutationStoreValue.error = null;
}
const storeResult: typeof result = { ...result };
if (typeof refetchQueries === "function") {
refetchQueries = refetchQueries(
storeResult as FetchResult<Unmasked<TData>>
);
}
if (errorPolicy === "ignore" && graphQLResultHasError(storeResult)) {
delete storeResult.errors;
}
return self.markMutationResult<TData, TVariables, TContext, TCache>({
mutationId,
result: storeResult,
document: mutation,
variables,
fetchPolicy,
errorPolicy,
context,
update: updateWithProxyFn,
updateQueries,
awaitRefetchQueries,
refetchQueries,
removeOptimistic: isOptimistic ? mutationId : void 0,
onQueryUpdated,
keepRootFields,
});
}
).subscribe({
next(storeResult) {
self.broadcastQueries();
// Since mutations might receive multiple payloads from the
// ApolloLink chain (e.g. when used with @defer),
// we resolve with a SingleExecutionResult or after the final
// ExecutionPatchResult has arrived and we have assembled the
// multipart response into a single result.
if (!("hasNext" in storeResult) || storeResult.hasNext === false) {
resolve({
...storeResult,
data: self.maskOperation({
document: mutation,
data: storeResult.data,
fetchPolicy,
id: mutationId,
}) as any,
});
}
},
error(err: Error) {
if (mutationStoreValue) {
mutationStoreValue.loading = false;
mutationStoreValue.error = err;
}
if (isOptimistic) {
self.cache.removeOptimistic(mutationId);
}
self.broadcastQueries();
reject(
err instanceof ApolloError ? err : (
new ApolloError({
networkError: err,
})
)
);
},
});
});
}
public markMutationResult<
TData,
TVariables,
TContext,
TCache extends ApolloCache<any>,
>(
mutation: {
mutationId: string;
result: FetchResult<TData>;
document: DocumentNode;
variables?: TVariables;
fetchPolicy?: MutationFetchPolicy;
errorPolicy: ErrorPolicy;
context?: TContext;
updateQueries: UpdateQueries<TData>;
update?: MutationUpdaterFunction<TData, TVariables, TContext, TCache>;
awaitRefetchQueries?: boolean;
refetchQueries?: InternalRefetchQueriesInclude;
removeOptimistic?: string;
onQueryUpdated?: OnQueryUpdated<any>;
keepRootFields?: boolean;
},
cache = this.cache
): Promise<FetchResult<TData>> {
let { result } = mutation;
const cacheWrites: Cache.WriteOptions[] = [];
const skipCache = mutation.fetchPolicy === "no-cache";
if (!skipCache && shouldWriteResult(result, mutation.errorPolicy)) {
if (!isExecutionPatchIncrementalResult(result)) {
cacheWrites.push({
result: result.data,
dataId: "ROOT_MUTATION",
query: mutation.document,
variables: mutation.variables,
});
}
if (
isExecutionPatchIncrementalResult(result) &&
isNonEmptyArray(result.incremental)
) {
const diff = cache.diff<TData>({
id: "ROOT_MUTATION",
// The cache complains if passed a mutation where it expects a
// query, so we transform mutations and subscriptions to queries
// (only once, thanks to this.transformCache).
query: this.getDocumentInfo(mutation.document).asQuery,
variables: mutation.variables,
optimistic: false,
returnPartialData: true,
});
let mergedData;
if (diff.result) {
mergedData = mergeIncrementalData(diff.result, result);
}
if (typeof mergedData !== "undefined") {
// cast the ExecutionPatchResult to FetchResult here since
// ExecutionPatchResult never has `data` when returned from the server
(result as FetchResult).data = mergedData;
cacheWrites.push({
result: mergedData,
dataId: "ROOT_MUTATION",
query: mutation.document,
variables: mutation.variables,
});
}
}
const { updateQueries } = mutation;
if (updateQueries) {
this.queries.forEach(({ observableQuery }, queryId) => {
const queryName = observableQuery && observableQuery.queryName;
if (!queryName || !hasOwnProperty.call(updateQueries, queryName)) {
return;
}
const updater = updateQueries[queryName];
const { document, variables } = this.queries.get(queryId)!;
// Read the current query result from the store.
const { result: currentQueryResult, complete } = cache.diff<TData>({
query: document!,
variables,
returnPartialData: true,
optimistic: false,
});
if (complete && currentQueryResult) {
// Run our reducer using the current query result and the mutation result.
const nextQueryResult = updater(currentQueryResult, {
mutationResult: result as FetchResult<Unmasked<TData>>,
queryName: (document && getOperationName(document)) || void 0,
queryVariables: variables!,
});
// Write the modified result back into the store if we got a new result.
if (nextQueryResult) {
cacheWrites.push({
result: nextQueryResult,
dataId: "ROOT_QUERY",
query: document!,
variables,
});
}
}
});
}
}
if (
cacheWrites.length > 0 ||
(mutation.refetchQueries || "").length > 0 ||
mutation.update ||
mutation.onQueryUpdated ||
mutation.removeOptimistic
) {
const results: any[] = [];
this.refetchQueries({
updateCache: (cache) => {
if (!skipCache) {
cacheWrites.forEach((write) => cache.write(write));
}
// If the mutation has some writes associated with it then we need to
// apply those writes to the store by running this reducer again with
// a write action.
const { update } = mutation;
// Determine whether result is a SingleExecutionResult,
// or the final ExecutionPatchResult.
const isFinalResult =
!isExecutionPatchResult(result) ||
(isExecutionPatchIncrementalResult(result) && !result.hasNext);
if (update) {
if (!skipCache) {
// Re-read the ROOT_MUTATION data we just wrote into the cache
// (the first cache.write call in the cacheWrites.forEach loop
// above), so field read functions have a chance to run for
// fields within mutation result objects.
const diff = cache.diff<TData>({
id: "ROOT_MUTATION",
// The cache complains if passed a mutation where it expects a
// query, so we transform mutations and subscriptions to queries
// (only once, thanks to this.transformCache).
query: this.getDocumentInfo(mutation.document).asQuery,
variables: mutation.variables,
optimistic: false,
returnPartialData: true,
});
if (diff.complete) {
result = { ...(result as FetchResult), data: diff.result };
if ("incremental" in result) {
delete result.incremental;
}
if ("hasNext" in result) {
delete result.hasNext;
}
}
}
// If we've received the whole response,
// either a SingleExecutionResult or the final ExecutionPatchResult,
// call the update function.
if (isFinalResult) {
update(cache as TCache, result as FetchResult<Unmasked<TData>>, {
context: mutation.context,
variables: mutation.variables,
});
}
}
// TODO Do this with cache.evict({ id: 'ROOT_MUTATION' }) but make it
// shallow to allow rolling back optimistic evictions.
if (!skipCache && !mutation.keepRootFields && isFinalResult) {
cache.modify({
id: "ROOT_MUTATION",
fields(value, { fieldName, DELETE }) {
return fieldName === "__typename" ? value : DELETE;
},
});
}
},
include: mutation.refetchQueries,
// Write the final mutation.result to the root layer of the cache.
optimistic: false,
// Remove the corresponding optimistic layer at the same time as we
// write the final non-optimistic result.
removeOptimistic: mutation.removeOptimistic,
// Let the caller of client.mutate optionally determine the refetching
// behavior for watched queries after the mutation.update function runs.
// If no onQueryUpdated function was provided for this mutation, pass
// null instead of undefined to disable the default refetching behavior.
onQueryUpdated: mutation.onQueryUpdated || null,
}).forEach((result) => results.push(result));
if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {
// Returning a promise here makes the mutation await that promise, so we
// include results in that promise's work if awaitRefetchQueries or an
// onQueryUpdated function was specified.
return Promise.all(results).then(() => result);
}
}
return Promise.resolve(result);
}
public markMutationOptimistic<
TData,
TVariables,
TContext,
TCache extends ApolloCache<any>,
>(
optimisticResponse: any,
mutation: {
mutationId: string;
document: DocumentNode;
variables?: TVariables;
fetchPolicy?: MutationFetchPolicy;
errorPolicy: ErrorPolicy;
context?: TContext;
updateQueries: UpdateQueries<TData>;
update?: MutationUpdaterFunction<TData, TVariables, TContext, TCache>;
keepRootFields?: boolean;
}
) {
const data =
typeof optimisticResponse === "function" ?
optimisticResponse(mutation.variables, { IGNORE })
: optimisticResponse;
if (data === IGNORE) {
return false;
}
this.cache.recordOptimisticTransaction((cache) => {
try {
this.markMutationResult<TData, TVariables, TContext, TCache>(
{
...mutation,
result: { data },
},
cache
);
} catch (error) {
invariant.error(error);
}
}, mutation.mutationId);
return true;
}
public fetchQuery<TData, TVars extends OperationVariables>(
queryId: string,
options: WatchQueryOptions<TVars, TData>,
networkStatus?: NetworkStatus
): Promise<ApolloQueryResult<TData>> {
return this.fetchConcastWithInfo(queryId, options, networkStatus).concast
.promise as TODO;
}
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 = [];
}
}
public transform(document: DocumentNode) {
return this.documentTransform.transformDocument(document);
}
private transformCache = new AutoCleanedWeakCache<
DocumentNode,
TransformCacheEntry
>(
cacheSizes["queryManager.getDocumentInfo"] ||
defaultCacheSizes["queryManager.getDocumentInfo"]
);
public getDocumentInfo(document: DocumentNode) {
const { transformCache } = this;
if (!transformCache.has(document)) {
const cacheEntry: TransformCacheEntry = {
// TODO These three calls (hasClientExports, shouldForceResolvers, and
// usesNonreactiveDirective) are performing independent full traversals
// of the transformed document. We should consider merging these
// traversals into a single pass in the future, though the work is
// cached after the first time.
hasClientExports: hasClientExports(document),
hasForcedResolvers: this.localState.shouldForceResolvers(document),
hasNonreactiveDirective: hasDirectives(["nonreactive"], document),
nonReactiveQuery: addNonReactiveToNamedFragments(document),
clientQuery: this.localState.clientQuery(document),
serverQuery: removeDirectivesFromDocument(
[
{ name: "client", remove: true },
{ name: "connection" },
{ name: "nonreactive" },
{ name: "unmask" },
],
document
),
defaultVars: getDefaultValues(
getOperationDefinition(document)
) as OperationVariables,
// Transform any mutation or subscription operations to query operations
// so we can read/write them from/to the cache.
asQuery: {
...document,
definitions: document.definitions.map((def) => {
if (
def.kind === "OperationDefinition" &&
def.operation !== "query"
) {
return { ...def, operation: "query" as OperationTypeNode };
}
return def;
}),
},
};
transformCache.set(document, cacheEntry);
}
return transformCache.get(document)!;
}
private getVariables<TVariables>(
document: DocumentNode,
variables?: TVariables
): OperationVariables {
return {
...this.getDocumentInfo(document).defaultVars,
...variables,
};
}
public watchQuery<
T,
TVariables extends OperationVariables = OperationVariables,
>(options: WatchQueryOptions<TVariables, T>): ObservableQuery<T, TVariables> {
const query = this.transform(options.query);
// assign variable default values if supplied
// NOTE: We don't modify options.query here with the transformed query to
// ensure observable.options.query is set to the raw untransformed query.
options = {
...options,
variables: this.getVariables(query, options.variables) as TVariables,
};
if (typeof options.notifyOnNetworkStatusChange === "undefined") {
options.notifyOnNetworkStatusChange = false;
}
const queryInfo = new QueryInfo(this);
const observable = new ObservableQuery<T, TVariables>({
queryManager: this,
queryInfo,
options,
});
observable["lastQuery"] = query;
this.queries.set(observable.queryId, queryInfo);
// We give queryInfo the transformed query to ensure the first cache diff
// uses the transformed query instead of the raw query
queryInfo.init({
document: query,
observableQuery: observable,
variables: observable.variables,
});
return observable;
}
public query<TData, TVars extends OperationVariables = OperationVariables>(
options: QueryOptions<TVars, TData>,
queryId = this.generateQueryId()
): Promise<ApolloQueryResult<MaybeMasked<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 query = this.transform(options.query);
return this.fetchQuery<TData, TVars>(queryId, { ...options, query })
.then(
(result) =>
result && {
...result,
data: this.maskOperation({
document: query,
data: result.data,
fetchPolicy: options.fetchPolicy,
id: queryId,
}),
}
)
.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(
options: Cache.ResetOptions = {
discardWatches: true,
}
): 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(
newInvariantError(
"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();
}
});
if (this.mutationStore) {
this.mutationStore = Object.create(null);
}
// begin removing data from the store
return this.cache.reset(options);
}
public getObservableQueries(
include: InternalRefetchQueriesInclude = "active"
) {
const queries = new Map<string, ObservableQuery<any>>();
const queryNames = new Map<string, string | null>();
const queryNamesAndQueryStrings = new Map<string, boolean>();
const legacyQueryOptions = new Set<QueryOptions>();
if (Array.isArray(include)) {
include.forEach((desc) => {
if (typeof desc === "string") {
queryNames.set(desc, desc);
queryNamesAndQueryStrings.set(desc, false);
} else if (isDocumentNode(desc)) {
const queryString = print(this.transform(desc));
queryNames.set(queryString, getOperationName(desc));
queryNamesAndQueryStrings.set(queryString, false);
} else if (isNonNullObject(desc) && desc.query) {
legacyQueryOptions.add(desc);
}
});
}
this.queries.forEach(({ observableQuery: oq, document }, queryId) => {
if (oq) {
if (include === "all") {
queries.set(queryId, oq);
return;
}
const {
queryName,
options: { fetchPolicy },
} = oq;
if (
fetchPolicy === "standby" ||
(include === "active" && !oq.hasObservers())
) {
return;
}
if (
include === "active" ||
(queryName && queryNamesAndQueryStrings.has(queryName)) ||
(document && queryNamesAndQueryStrings.has(print(document)))
) {
queries.set(queryId, oq);
if (queryName) queryNamesAndQueryStrings.set(queryName, true);
if (document) queryNamesAndQueryStrings.set(print(document), true);
}
}
});
if (legacyQueryOptions.size) {
legacyQueryOptions.forEach((options: QueryOptions) => {
// We will be issuing a fresh network request for this query, so we
// pre-allocate a new query ID here, using a special prefix to enable
// cleaning up these temporary queries later, after fetching.
const queryId = makeUniqueId("legacyOneTimeQuery");
const queryInfo = this.getQuery(queryId).init({
document: options.query,
variables: options.variables,
});
const oq = new ObservableQuery({
queryManager: this,
queryInfo,
options: {
...options,
fetchPolicy: "network-only",
},
});
invariant(oq.queryId === queryId);
queryInfo.setObservableQuery(oq);
queries.set(queryId, oq);
});
}
if (__DEV__ && queryNamesAndQueryStrings.size) {
queryNamesAndQueryStrings.forEach((included, nameOrQueryString) => {
if (!included) {
const queryName = queryNames.get(nameOrQueryString);
if (queryName) {
invariant.warn(
`Unknown query named "%s" requested in refetchQueries options.include array`,
queryName
);
} else {
invariant.warn(
`Unknown anonymous query requested in refetchQueries options.include array`
);
}
}
});
}
return queries;
}
public reFetchObservableQueries(
includeStandby: boolean = false
): Promise<ApolloQueryResult<any>[]> {