-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathApolloClient.ts
910 lines (835 loc) · 31.4 KB
/
ApolloClient.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
import { invariant, newInvariantError } from "../utilities/globals/index.js";
import type { DocumentNode, FormattedExecutionResult } from "graphql";
import type { FetchResult, GraphQLRequest } from "../link/core/index.js";
import { ApolloLink, execute } from "../link/core/index.js";
import type { ApolloCache, DataProxy, Reference } from "../cache/index.js";
import type { DocumentTransform, Observable } from "../utilities/index.js";
import { version } from "../version.js";
import type { UriFunction } from "../link/http/index.js";
import { HttpLink } from "../link/http/index.js";
import { QueryManager } from "./QueryManager.js";
import type { ObservableQuery } from "./ObservableQuery.js";
import type {
ApolloQueryResult,
DefaultContext,
OperationVariables,
Resolvers,
RefetchQueriesOptions,
RefetchQueriesResult,
InternalRefetchQueriesResult,
RefetchQueriesInclude,
} from "./types.js";
import type {
QueryOptions,
WatchQueryOptions,
MutationOptions,
SubscriptionOptions,
WatchQueryFetchPolicy,
} from "./watchQueryOptions.js";
import type { FragmentMatcher } from "./LocalState.js";
import { LocalState } from "./LocalState.js";
export interface DefaultOptions {
watchQuery?: Partial<WatchQueryOptions<any, any>>;
query?: Partial<QueryOptions<any, any>>;
mutate?: Partial<MutationOptions<any, any, any>>;
}
export interface DevtoolsOptions {
/**
* If `true`, the [Apollo Client Devtools](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) browser extension can connect to this `ApolloClient` instance.
*
* The default value is `false` in production and `true` in development if there is a `window` object.
*/
enabled?: boolean;
/**
* Optional name for this `ApolloClient` instance in the devtools. This is
* useful when you instantiate multiple clients and want to be able to
* identify them by name.
*/
name?: string;
}
let hasSuggestedDevtools = false;
export interface ApolloClientOptions<TCacheShape> {
/**
* The URI of the GraphQL endpoint that Apollo Client will communicate with.
*
* One of `uri` or `link` is **required**. If you provide both, `link` takes precedence.
*/
uri?: string | UriFunction;
credentials?: string;
/**
* An object representing headers to include in every HTTP request, such as `{Authorization: 'Bearer 1234'}`
*
* This value will be ignored when using the `link` option.
*/
headers?: Record<string, string>;
/**
* You can provide an `ApolloLink` instance to serve as Apollo Client's network layer. For more information, see [Advanced HTTP networking](https://www.apollographql.com/docs/react/networking/advanced-http-networking/).
*
* One of `uri` or `link` is **required**. If you provide both, `link` takes precedence.
*/
link?: ApolloLink;
/**
* The cache that Apollo Client should use to store query results locally. The recommended cache is `InMemoryCache`, which is provided by the `@apollo/client` package.
*
* For more information, see [Configuring the cache](https://www.apollographql.com/docs/react/caching/cache-configuration/).
*/
cache: ApolloCache<TCacheShape>;
/**
* The time interval (in milliseconds) before Apollo Client force-fetches queries after a server-side render.
*
* @defaultValue `0` (no delay)
*/
ssrForceFetchDelay?: number;
/**
* When using Apollo Client for [server-side rendering](https://www.apollographql.com/docs/react/performance/server-side-rendering/), set this to `true` so that the [`getDataFromTree` function](../react/ssr/#getdatafromtree) can work effectively.
*
* @defaultValue `false`
*/
ssrMode?: boolean;
/**
* If `true`, the [Apollo Client Devtools](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) browser extension can connect to Apollo Client.
*
* The default value is `false` in production and `true` in development (if there is a `window` object).
* @deprecated Please use the `devtools.enabled` option.
*/
connectToDevTools?: boolean;
/**
* If `false`, Apollo Client sends every created query to the server, even if a _completely_ identical query (identical in terms of query string, variable values, and operationName) is already in flight.
*
* @defaultValue `true`
*/
queryDeduplication?: boolean;
/**
* Provide this object to set application-wide default values for options you can provide to the `watchQuery`, `query`, and `mutate` functions. See below for an example object.
*
* See this [example object](https://www.apollographql.com/docs/react/api/core/ApolloClient#example-defaultoptions-object).
*/
defaultOptions?: DefaultOptions;
defaultContext?: Partial<DefaultContext>;
/**
* If `true`, Apollo Client will assume results read from the cache are never mutated by application code, which enables substantial performance optimizations.
*
* @defaultValue `false`
*/
assumeImmutableResults?: boolean;
resolvers?: Resolvers | Resolvers[];
typeDefs?: string | string[] | DocumentNode | DocumentNode[];
fragmentMatcher?: FragmentMatcher;
/**
* A custom name (e.g., `iOS`) that identifies this particular client among your set of clients. Apollo Server and Apollo Studio use this property as part of the [client awareness](https://www.apollographql.com/docs/apollo-server/monitoring/metrics#identifying-distinct-clients) feature.
*/
name?: string;
/**
* A custom version that identifies the current version of this particular client (e.g., `1.2`). Apollo Server and Apollo Studio use this property as part of the [client awareness](https://www.apollographql.com/docs/apollo-server/monitoring/metrics#identifying-distinct-clients) feature.
*
* This is **not** the version of Apollo Client that you are using, but rather any version string that helps you differentiate between versions of your client.
*/
version?: string;
documentTransform?: DocumentTransform;
/**
* Configuration used by the [Apollo Client Devtools extension](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) for this client.
*
* @since 3.11.0
*/
devtools?: DevtoolsOptions;
}
// Though mergeOptions now resides in @apollo/client/utilities, it was
// previously declared and exported from this module, and then reexported from
// @apollo/client/core. Since we need to preserve that API anyway, the easiest
// solution is to reexport mergeOptions where it was previously declared (here).
import { mergeOptions } from "../utilities/index.js";
import { getApolloClientMemoryInternals } from "../utilities/caching/getMemoryInternals.js";
import type {
WatchFragmentOptions,
WatchFragmentResult,
} from "../cache/core/cache.js";
export { mergeOptions };
/**
* This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries
* and mutations) to a GraphQL spec-compliant server over an `ApolloLink` instance,
* receive results from the server and cache the results in a store. It also delivers updates
* to GraphQL queries through `Observable` instances.
*/
export class ApolloClient<TCacheShape> implements DataProxy {
public link: ApolloLink;
public cache: ApolloCache<TCacheShape>;
public disableNetworkFetches: boolean;
public version: string;
public queryDeduplication: boolean;
public defaultOptions: DefaultOptions;
public readonly typeDefs: ApolloClientOptions<TCacheShape>["typeDefs"];
public readonly devtoolsConfig: DevtoolsOptions;
private queryManager: QueryManager<TCacheShape>;
private devToolsHookCb?: Function;
private resetStoreCallbacks: Array<() => Promise<any>> = [];
private clearStoreCallbacks: Array<() => Promise<any>> = [];
private localState: LocalState<TCacheShape>;
/**
* Constructs an instance of `ApolloClient`.
*
* @example
* ```js
* import { ApolloClient, InMemoryCache } from '@apollo/client';
*
* const cache = new InMemoryCache();
*
* const client = new ApolloClient({
* // Provide required constructor fields
* cache: cache,
* uri: 'http://localhost:4000/',
*
* // Provide some optional constructor fields
* name: 'react-web-client',
* version: '1.3',
* queryDeduplication: false,
* defaultOptions: {
* watchQuery: {
* fetchPolicy: 'cache-and-network',
* },
* },
* });
* ```
*/
constructor(options: ApolloClientOptions<TCacheShape>) {
if (!options.cache) {
throw newInvariantError(
"To initialize Apollo Client, you must specify a 'cache' property " +
"in the options object. \n" +
"For more information, please visit: https://go.apollo.dev/c/docs"
);
}
const {
uri,
credentials,
headers,
cache,
documentTransform,
ssrMode = false,
ssrForceFetchDelay = 0,
// Expose the client instance as window.__APOLLO_CLIENT__ and call
// onBroadcast in queryManager.broadcastQueries to enable browser
// devtools, but disable them by default in production.
connectToDevTools,
queryDeduplication = true,
defaultOptions,
defaultContext,
assumeImmutableResults = cache.assumeImmutableResults,
resolvers,
typeDefs,
fragmentMatcher,
name: clientAwarenessName,
version: clientAwarenessVersion,
devtools,
} = options;
let { link } = options;
if (!link) {
link =
uri ? new HttpLink({ uri, credentials, headers }) : ApolloLink.empty();
}
this.link = link;
this.cache = cache;
this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
this.queryDeduplication = queryDeduplication;
this.defaultOptions = defaultOptions || Object.create(null);
this.typeDefs = typeDefs;
this.devtoolsConfig = {
...devtools,
enabled: devtools?.enabled || connectToDevTools,
};
if (this.devtoolsConfig.enabled === undefined) {
this.devtoolsConfig.enabled = __DEV__;
}
if (ssrForceFetchDelay) {
setTimeout(
() => (this.disableNetworkFetches = false),
ssrForceFetchDelay
);
}
this.watchQuery = this.watchQuery.bind(this);
this.query = this.query.bind(this);
this.mutate = this.mutate.bind(this);
this.watchFragment = this.watchFragment.bind(this);
this.resetStore = this.resetStore.bind(this);
this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);
this.version = version;
this.localState = new LocalState({
cache,
client: this,
resolvers,
fragmentMatcher,
});
this.queryManager = new QueryManager({
cache: this.cache,
link: this.link,
defaultOptions: this.defaultOptions,
defaultContext,
documentTransform,
queryDeduplication,
ssrMode,
clientAwareness: {
name: clientAwarenessName!,
version: clientAwarenessVersion!,
},
localState: this.localState,
assumeImmutableResults,
onBroadcast:
this.devtoolsConfig.enabled ?
() => {
if (this.devToolsHookCb) {
this.devToolsHookCb({
action: {},
state: {
queries: this.queryManager.getQueryStore(),
mutations: this.queryManager.mutationStore || {},
},
dataWithOptimisticResults: this.cache.extract(true),
});
}
}
: void 0,
});
if (this.devtoolsConfig.enabled) this.connectToDevTools();
}
private connectToDevTools() {
if (typeof window === "undefined") {
return;
}
type DevToolsConnector = {
push(client: ApolloClient<any>): void;
};
const windowWithDevTools = window as Window & {
[devtoolsSymbol]?: DevToolsConnector;
__APOLLO_CLIENT__?: ApolloClient<any>;
};
const devtoolsSymbol = Symbol.for("apollo.devtools");
(windowWithDevTools[devtoolsSymbol] =
windowWithDevTools[devtoolsSymbol] || ([] as DevToolsConnector)).push(
this
);
windowWithDevTools.__APOLLO_CLIENT__ = this;
/**
* Suggest installing the devtools for developers who don't have them
*/
if (!hasSuggestedDevtools && __DEV__) {
hasSuggestedDevtools = true;
if (
window.document &&
window.top === window.self &&
/^(https?|file):$/.test(window.location.protocol)
) {
setTimeout(() => {
if (!(window as any).__APOLLO_DEVTOOLS_GLOBAL_HOOK__) {
const nav = window.navigator;
const ua = nav && nav.userAgent;
let url: string | undefined;
if (typeof ua === "string") {
if (ua.indexOf("Chrome/") > -1) {
url =
"https://chrome.google.com/webstore/detail/" +
"apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm";
} else if (ua.indexOf("Firefox/") > -1) {
url =
"https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/";
}
}
if (url) {
invariant.log(
"Download the Apollo DevTools for a better development " +
"experience: %s",
url
);
}
}
}, 10000);
}
}
}
/**
* The `DocumentTransform` used to modify GraphQL documents before a request
* is made. If a custom `DocumentTransform` is not provided, this will be the
* default document transform.
*/
get documentTransform() {
return this.queryManager.documentTransform;
}
/**
* Call this method to terminate any active client processes, making it safe
* to dispose of this `ApolloClient` instance.
*/
public stop() {
this.queryManager.stop();
}
/**
* This watches the cache store of the query according to the options specified and
* returns an `ObservableQuery`. We can subscribe to this `ObservableQuery` and
* receive updated results through an observer when the cache store changes.
*
* Note that this method is not an implementation of GraphQL subscriptions. Rather,
* it uses Apollo's store in order to reactively deliver updates to your query results.
*
* For example, suppose you call watchQuery on a GraphQL query that fetches a person's
* first and last name and this person has a particular object identifier, provided by
* dataIdFromObject. Later, a different query fetches that same person's
* first and last name and the first name has now changed. Then, any observers associated
* with the results of the first query will be updated with a new result object.
*
* Note that if the cache does not change, the subscriber will *not* be notified.
*
* See [here](https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3#.3mb0cbcmc) for
* a description of store reactivity.
*/
public watchQuery<
T = any,
TVariables extends OperationVariables = OperationVariables,
>(options: WatchQueryOptions<TVariables, T>): ObservableQuery<T, TVariables> {
if (this.defaultOptions.watchQuery) {
options = mergeOptions(this.defaultOptions.watchQuery, options);
}
// XXX Overwriting options is probably not the best way to do this long term...
if (
this.disableNetworkFetches &&
(options.fetchPolicy === "network-only" ||
options.fetchPolicy === "cache-and-network")
) {
options = { ...options, fetchPolicy: "cache-first" };
}
return this.queryManager.watchQuery<T, TVariables>(options);
}
/**
* This resolves a single query according to the options specified and
* returns a `Promise` which is either resolved with the resulting data
* or rejected with an error.
*
* @param options - An object of type `QueryOptions` that allows us to
* describe how this query should be treated e.g. whether it should hit the
* server at all or just resolve from the cache, etc.
*/
public query<
T = any,
TVariables extends OperationVariables = OperationVariables,
>(options: QueryOptions<TVariables, T>): Promise<ApolloQueryResult<T>> {
if (this.defaultOptions.query) {
options = mergeOptions(this.defaultOptions.query, options);
}
invariant(
(options.fetchPolicy as WatchQueryFetchPolicy) !== "cache-and-network",
"The cache-and-network fetchPolicy does not work with client.query, because " +
"client.query can only return a single result. Please use client.watchQuery " +
"to receive multiple results from the cache and the network, or consider " +
"using a different fetchPolicy, such as cache-first or network-only."
);
if (this.disableNetworkFetches && options.fetchPolicy === "network-only") {
options = { ...options, fetchPolicy: "cache-first" };
}
return this.queryManager.query<T, TVariables>(options);
}
/**
* This resolves a single mutation according to the options specified and returns a
* Promise which is either resolved with the resulting data or rejected with an
* error. In some cases both `data` and `errors` might be undefined, for example
* when `errorPolicy` is set to `'ignore'`.
*
* It takes options as an object with the following keys and values:
*/
public mutate<
TData = any,
TVariables extends OperationVariables = OperationVariables,
TContext extends Record<string, any> = DefaultContext,
TCache extends ApolloCache<any> = ApolloCache<any>,
>(
options: MutationOptions<TData, TVariables, TContext>
): Promise<FetchResult<TData>> {
if (this.defaultOptions.mutate) {
options = mergeOptions(this.defaultOptions.mutate, options);
}
return this.queryManager.mutate<TData, TVariables, TContext, TCache>(
options
);
}
/**
* This subscribes to a graphql subscription according to the options specified and returns an
* `Observable` which either emits received data or an error.
*/
public subscribe<
T = any,
TVariables extends OperationVariables = OperationVariables,
>(options: SubscriptionOptions<TVariables, T>): Observable<FetchResult<T>> {
return this.queryManager.startGraphQLSubscription<T>(options);
}
/**
* Tries to read some data from the store in the shape of the provided
* GraphQL query without making a network request. This method will start at
* the root query. To start at a specific id returned by `dataIdFromObject`
* use `readFragment`.
*
* @param optimistic - Set to `true` to allow `readQuery` to return
* optimistic results. Is `false` by default.
*/
public readQuery<T = any, TVariables = OperationVariables>(
options: DataProxy.Query<TVariables, T>,
optimistic: boolean = false
): T | null {
return this.cache.readQuery<T, TVariables>(options, optimistic);
}
/**
* Watches the cache store of the fragment according to the options specified
* and returns an `Observable`. We can subscribe to this
* `Observable` and receive updated results through an
* observer when the cache store changes.
*
* You must pass in a GraphQL document with a single fragment or a document
* with multiple fragments that represent what you are reading. If you pass
* in a document with multiple fragments then you must also specify a
* `fragmentName`.
*
* @since 3.10.0
* @param options - An object of type `WatchFragmentOptions` that allows
* the cache to identify the fragment and optionally specify whether to react
* to optimistic updates.
*/
public watchFragment<
TFragmentData = unknown,
TVariables = OperationVariables,
>(
options: WatchFragmentOptions<TFragmentData, TVariables>
): Observable<WatchFragmentResult<TFragmentData>> {
return this.cache.watchFragment<TFragmentData, TVariables>(options);
}
/**
* Tries to read some data from the store in the shape of the provided
* GraphQL fragment without making a network request. This method will read a
* GraphQL fragment from any arbitrary id that is currently cached, unlike
* `readQuery` which will only read from the root query.
*
* You must pass in a GraphQL document with a single fragment or a document
* with multiple fragments that represent what you are reading. If you pass
* in a document with multiple fragments then you must also specify a
* `fragmentName`.
*
* @param optimistic - Set to `true` to allow `readFragment` to return
* optimistic results. Is `false` by default.
*/
public readFragment<T = any, TVariables = OperationVariables>(
options: DataProxy.Fragment<TVariables, T>,
optimistic: boolean = false
): T | null {
return this.cache.readFragment<T, TVariables>(options, optimistic);
}
/**
* Writes some data in the shape of the provided GraphQL query directly to
* the store. This method will start at the root query. To start at a
* specific id returned by `dataIdFromObject` then use `writeFragment`.
*/
public writeQuery<TData = any, TVariables = OperationVariables>(
options: DataProxy.WriteQueryOptions<TData, TVariables>
): Reference | undefined {
const ref = this.cache.writeQuery<TData, TVariables>(options);
if (options.broadcast !== false) {
this.queryManager.broadcastQueries();
}
return ref;
}
/**
* Writes some data in the shape of the provided GraphQL fragment directly to
* the store. This method will write to a GraphQL fragment from any arbitrary
* id that is currently cached, unlike `writeQuery` which will only write
* from the root query.
*
* You must pass in a GraphQL document with a single fragment or a document
* with multiple fragments that represent what you are writing. If you pass
* in a document with multiple fragments then you must also specify a
* `fragmentName`.
*/
public writeFragment<TData = any, TVariables = OperationVariables>(
options: DataProxy.WriteFragmentOptions<TData, TVariables>
): Reference | undefined {
const ref = this.cache.writeFragment<TData, TVariables>(options);
if (options.broadcast !== false) {
this.queryManager.broadcastQueries();
}
return ref;
}
public __actionHookForDevTools(cb: () => any) {
this.devToolsHookCb = cb;
}
public __requestRaw(
payload: GraphQLRequest
): Observable<FormattedExecutionResult> {
return execute(this.link, payload);
}
/**
* Resets your entire store by clearing out your cache and then re-executing
* all of your active queries. This makes it so that you may guarantee that
* there is no data left in your store from a time before you called this
* method.
*
* `resetStore()` is useful when your user just logged out. You’ve removed the
* user session, and you now want to make sure that any references to data you
* might have fetched while the user session was active is gone.
*
* It is important to remember that `resetStore()` *will* refetch any active
* queries. This means that any components that might be mounted will execute
* their queries again using your network interface. If you do not want to
* re-execute any queries then you should make sure to stop watching any
* active queries.
*/
public resetStore(): Promise<ApolloQueryResult<any>[] | null> {
return Promise.resolve()
.then(() =>
this.queryManager.clearStore({
discardWatches: false,
})
)
.then(() => Promise.all(this.resetStoreCallbacks.map((fn) => fn())))
.then(() => this.reFetchObservableQueries());
}
/**
* Remove all data from the store. Unlike `resetStore`, `clearStore` will
* not refetch any active queries.
*/
public clearStore(): Promise<any[]> {
return Promise.resolve()
.then(() =>
this.queryManager.clearStore({
discardWatches: true,
})
)
.then(() => Promise.all(this.clearStoreCallbacks.map((fn) => fn())));
}
/**
* Allows callbacks to be registered that are executed when the store is
* reset. `onResetStore` returns an unsubscribe function that can be used
* to remove registered callbacks.
*/
public onResetStore(cb: () => Promise<any>): () => void {
this.resetStoreCallbacks.push(cb);
return () => {
this.resetStoreCallbacks = this.resetStoreCallbacks.filter(
(c) => c !== cb
);
};
}
/**
* Allows callbacks to be registered that are executed when the store is
* cleared. `onClearStore` returns an unsubscribe function that can be used
* to remove registered callbacks.
*/
public onClearStore(cb: () => Promise<any>): () => void {
this.clearStoreCallbacks.push(cb);
return () => {
this.clearStoreCallbacks = this.clearStoreCallbacks.filter(
(c) => c !== cb
);
};
}
/**
* Refetches all of your active queries.
*
* `reFetchObservableQueries()` is useful if you want to bring the client back to proper state in case of a network outage
*
* It is important to remember that `reFetchObservableQueries()` *will* refetch any active
* queries. This means that any components that might be mounted will execute
* their queries again using your network interface. If you do not want to
* re-execute any queries then you should make sure to stop watching any
* active queries.
* Takes optional parameter `includeStandby` which will include queries in standby-mode when refetching.
*/
public reFetchObservableQueries(
includeStandby?: boolean
): Promise<ApolloQueryResult<any>[]> {
return this.queryManager.reFetchObservableQueries(includeStandby);
}
/**
* Refetches specified active queries. Similar to "reFetchObservableQueries()" but with a specific list of queries.
*
* `refetchQueries()` is useful for use cases to imperatively refresh a selection of queries.
*
* It is important to remember that `refetchQueries()` *will* refetch specified active
* queries. This means that any components that might be mounted will execute
* their queries again using your network interface. If you do not want to
* re-execute any queries then you should make sure to stop watching any
* active queries.
*/
public refetchQueries<
TCache extends ApolloCache<any> = ApolloCache<TCacheShape>,
TResult = Promise<ApolloQueryResult<any>>,
>(
options: RefetchQueriesOptions<TCache, TResult>
): RefetchQueriesResult<TResult> {
const map = this.queryManager.refetchQueries(
options as RefetchQueriesOptions<ApolloCache<TCacheShape>, TResult>
);
const queries: ObservableQuery<any>[] = [];
const results: InternalRefetchQueriesResult<TResult>[] = [];
map.forEach((result, obsQuery) => {
queries.push(obsQuery);
results.push(result);
});
const result = Promise.all<TResult>(
results as TResult[]
) as RefetchQueriesResult<TResult>;
// In case you need the raw results immediately, without awaiting
// Promise.all(results):
result.queries = queries;
result.results = results;
// If you decide to ignore the result Promise because you're using
// result.queries and result.results instead, you shouldn't have to worry
// about preventing uncaught rejections for the Promise.all result.
result.catch((error) => {
invariant.debug(
`In client.refetchQueries, Promise.all promise rejected with error %o`,
error
);
});
return result;
}
/**
* Get all currently active `ObservableQuery` objects, in a `Map` keyed by
* query ID strings.
*
* An "active" query is one that has observers and a `fetchPolicy` other than
* "standby" or "cache-only".
*
* You can include all `ObservableQuery` objects (including the inactive ones)
* by passing "all" instead of "active", or you can include just a subset of
* active queries by passing an array of query names or DocumentNode objects.
*/
public getObservableQueries(
include: RefetchQueriesInclude = "active"
): Map<string, ObservableQuery<any>> {
return this.queryManager.getObservableQueries(include);
}
/**
* Exposes the cache's complete state, in a serializable format for later restoration.
*/
public extract(optimistic?: boolean): TCacheShape {
return this.cache.extract(optimistic);
}
/**
* Replaces existing state in the cache (if any) with the values expressed by
* `serializedState`.
*
* Called when hydrating a cache (server side rendering, or offline storage),
* and also (potentially) during hot reloads.
*/
public restore(serializedState: TCacheShape): ApolloCache<TCacheShape> {
return this.cache.restore(serializedState);
}
/**
* Add additional local resolvers.
*/
public addResolvers(resolvers: Resolvers | Resolvers[]) {
this.localState.addResolvers(resolvers);
}
/**
* Set (override existing) local resolvers.
*/
public setResolvers(resolvers: Resolvers | Resolvers[]) {
this.localState.setResolvers(resolvers);
}
/**
* Get all registered local resolvers.
*/
public getResolvers() {
return this.localState.getResolvers();
}
/**
* Set a custom local state fragment matcher.
*/
public setLocalStateFragmentMatcher(fragmentMatcher: FragmentMatcher) {
this.localState.setFragmentMatcher(fragmentMatcher);
}
/**
* Define a new ApolloLink (or link chain) that Apollo Client will use.
*/
public setLink(newLink: ApolloLink) {
this.link = this.queryManager.link = newLink;
}
public get defaultContext() {
return this.queryManager.defaultContext;
}
/**
* @experimental
* This is not a stable API - it is used in development builds to expose
* information to the DevTools.
* Use at your own risk!
* For more details, see [Memory Management](https://www.apollographql.com/docs/react/caching/memory-management/#measuring-cache-usage)
*
* @example
* ```ts
* console.log(client.getMemoryInternals())
* ```
* Logs output in the following JSON format:
* @example
* ```json
*{
* limits: {
* parser: 1000,
* canonicalStringify: 1000,
* print: 2000,
* 'documentTransform.cache': 2000,
* 'queryManager.getDocumentInfo': 2000,
* 'PersistedQueryLink.persistedQueryHashes': 2000,
* 'fragmentRegistry.transform': 2000,
* 'fragmentRegistry.lookup': 1000,
* 'fragmentRegistry.findFragmentSpreads': 4000,
* 'cache.fragmentQueryDocuments': 1000,
* 'removeTypenameFromVariables.getVariableDefinitions': 2000,
* 'inMemoryCache.maybeBroadcastWatch': 5000,
* 'inMemoryCache.executeSelectionSet': 10000,
* 'inMemoryCache.executeSubSelectedArray': 5000
* },
* sizes: {
* parser: 26,
* canonicalStringify: 4,
* print: 14,
* addTypenameDocumentTransform: [
* {
* cache: 14,
* },
* ],
* queryManager: {
* getDocumentInfo: 14,
* documentTransforms: [
* {
* cache: 14,
* },
* {
* cache: 14,
* },
* ],
* },
* fragmentRegistry: {
* findFragmentSpreads: 34,
* lookup: 20,
* transform: 14,
* },
* cache: {
* fragmentQueryDocuments: 22,
* },
* inMemoryCache: {
* executeSelectionSet: 4345,
* executeSubSelectedArray: 1206,
* maybeBroadcastWatch: 32,
* },
* links: [
* {
* PersistedQueryLink: {
* persistedQueryHashes: 14,
* },
* },
* {
* removeTypenameFromVariables: {
* getVariableDefinitions: 14,
* },
* },
* ],
* },
* }
*```
*/
public getMemoryInternals?: typeof getApolloClientMemoryInternals;
}
if (__DEV__) {
ApolloClient.prototype.getMemoryInternals = getApolloClientMemoryInternals;
}