-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
ApolloClient.ts
634 lines (575 loc) · 22.7 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
import { invariant, InvariantError } from '../utilities/globals';
import { ExecutionResult, DocumentNode } from 'graphql';
import { ApolloLink, FetchResult, GraphQLRequest, execute } from '../link/core';
import { ApolloCache, DataProxy } from '../cache';
import { Observable } from '../utilities';
import { version } from '../version';
import { HttpLink, UriFunction } from '../link/http';
import { QueryManager } from './QueryManager';
import { ObservableQuery } from './ObservableQuery';
import {
ApolloQueryResult,
DefaultContext,
OperationVariables,
Resolvers,
RefetchQueriesOptions,
RefetchQueriesResult,
InternalRefetchQueriesResult,
RefetchQueriesInclude,
} from './types';
import {
QueryOptions,
WatchQueryOptions,
MutationOptions,
SubscriptionOptions,
WatchQueryFetchPolicy,
} from './watchQueryOptions';
import {
LocalState,
FragmentMatcher,
} from './LocalState';
export interface DefaultOptions {
watchQuery?: Partial<WatchQueryOptions<any, any>>;
query?: Partial<QueryOptions<any, any>>;
mutate?: Partial<MutationOptions<any, any, any>>;
}
let hasSuggestedDevtools = false;
export type ApolloClientOptions<TCacheShape> = {
uri?: string | UriFunction;
credentials?: string;
headers?: Record<string, string>;
link?: ApolloLink;
cache: ApolloCache<TCacheShape>;
ssrForceFetchDelay?: number;
ssrMode?: boolean;
connectToDevTools?: boolean;
queryDeduplication?: boolean;
defaultOptions?: DefaultOptions;
assumeImmutableResults?: boolean;
resolvers?: Resolvers | Resolvers[];
typeDefs?: string | string[] | DocumentNode | DocumentNode[];
fragmentMatcher?: FragmentMatcher;
name?: string;
version?: string;
};
// 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";
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 a {@link NetworkInterface} instance,
* receive results from the server and cache the results in a store. It also delivers updates
* to GraphQL queries through {@link 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'];
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 {@link ApolloClient}.
*
* @param uri The GraphQL endpoint that Apollo Client will connect to. If
* `link` is configured, this option is ignored.
* @param link The {@link ApolloLink} over which GraphQL documents will be resolved into a response.
*
* @param cache The initial cache to use in the data store.
*
* @param ssrMode Determines whether this is being run in Server Side Rendering (SSR) mode.
*
* @param ssrForceFetchDelay Determines the time interval before we force fetch queries for a
* server side render.
*
* @param queryDeduplication If set to false, a query will still be sent to the server even if a query
* with identical parameters (query, variables, operationName) is already in flight.
*
* @param defaultOptions Used to set application wide defaults for the
* options supplied to `watchQuery`, `query`, or
* `mutate`.
*
* @param assumeImmutableResults When this option is true, the client will assume results
* read from the cache are never mutated by application code,
* which enables substantial performance optimizations. Passing
* `{ freezeResults: true }` to the `InMemoryCache` constructor
* can help enforce this immutability.
*
* @param name A custom name that can be used to identify this client, when
* using Apollo client awareness features. E.g. "iOS".
*
* @param version A custom version that can be used to identify this client,
* when using Apollo client awareness features. This is the
* version of your client, which you may want to increment on
* new builds. This is NOT the version of Apollo Client that
* you are using.
*/
constructor(options: ApolloClientOptions<TCacheShape>) {
const {
uri,
credentials,
headers,
cache,
ssrMode = false,
ssrForceFetchDelay = 0,
connectToDevTools =
// 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.
typeof window === 'object' &&
!(window as any).__APOLLO_CLIENT__ &&
__DEV__,
queryDeduplication = true,
defaultOptions,
assumeImmutableResults = false,
resolvers,
typeDefs,
fragmentMatcher,
name: clientAwarenessName,
version: clientAwarenessVersion,
} = options;
let { link } = options;
if (!link) {
link = uri
? new HttpLink({ uri, credentials, headers })
: ApolloLink.empty();
}
if (!cache) {
throw new InvariantError(
"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"
);
}
this.link = link;
this.cache = cache;
this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
this.queryDeduplication = queryDeduplication;
this.defaultOptions = defaultOptions || Object.create(null);
this.typeDefs = typeDefs;
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.resetStore = this.resetStore.bind(this);
this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);
if (connectToDevTools && typeof window === 'object') {
(window as any).__APOLLO_CLIENT__ = this;
}
/**
* Suggest installing the devtools for developers who don't have them
*/
if (!hasSuggestedDevtools && __DEV__) {
hasSuggestedDevtools = true;
if (
typeof window !== 'undefined' &&
window.document &&
window.top === window.self &&
!(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: " + url
);
}
}
}
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,
queryDeduplication,
ssrMode,
clientAwareness: {
name: clientAwarenessName!,
version: clientAwarenessVersion!,
},
localState: this.localState,
assumeImmutableResults,
onBroadcast: connectToDevTools ? () => {
if (this.devToolsHookCb) {
this.devToolsHookCb({
action: {},
state: {
queries: this.queryManager.getQueryStore(),
mutations: this.queryManager.mutationStore || {},
},
dataWithOptimisticResults: this.cache.extract(true),
});
}
} : void 0,
});
}
/**
* 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 {@link ObservableQuery}. We can subscribe to this {@link ObservableQuery} and
* receive updated results through a GraphQL 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 = 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 {@link Promise} which is either resolved with the resulting data
* or rejected with an error.
*
* @param options An object of type {@link 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 = 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
* {@link Promise} which is either resolved with the resulting data or rejected with an
* error.
*
* It takes options as an object with the following keys and values:
*/
public mutate<
TData = any,
TVariables = OperationVariables,
TContext = 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
* {@link Observable} which either emits received data or an error.
*/
public subscribe<T = any, TVariables = 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);
}
/**
* 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>,
): void {
this.cache.writeQuery<TData, TVariables>(options);
this.queryManager.broadcastQueries();
}
/**
* 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>,
): void {
this.cache.writeFragment<TData, TVariables>(options);
this.queryManager.broadcastQueries();
}
public __actionHookForDevTools(cb: () => any) {
this.devToolsHookCb = cb;
}
public __requestRaw(payload: GraphQLRequest): Observable<ExecutionResult> {
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);
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 ${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;
}
}