UNPKG

22.2 kBTypeScriptView Raw
1import type { DocumentNode, FormattedExecutionResult } from "graphql";
2import type { FetchResult, GraphQLRequest } from "../link/core/index.js";
3import { ApolloLink } from "../link/core/index.js";
4import type { ApolloCache, DataProxy, Reference } from "../cache/index.js";
5import type { DocumentTransform, Observable } from "../utilities/index.js";
6import type { UriFunction } from "../link/http/index.js";
7import type { ObservableQuery } from "./ObservableQuery.js";
8import type { ApolloQueryResult, DefaultContext, OperationVariables, Resolvers, RefetchQueriesOptions, RefetchQueriesResult, RefetchQueriesInclude } from "./types.js";
9import type { QueryOptions, WatchQueryOptions, MutationOptions, SubscriptionOptions } from "./watchQueryOptions.js";
10import type { FragmentMatcher } from "./LocalState.js";
11export interface DefaultOptions {
12 watchQuery?: Partial<WatchQueryOptions<any, any>>;
13 query?: Partial<QueryOptions<any, any>>;
14 mutate?: Partial<MutationOptions<any, any, any>>;
15}
16export interface DevtoolsOptions {
17 /**
18 * 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.
19 *
20 * The default value is `false` in production and `true` in development if there is a `window` object.
21 */
22 enabled?: boolean;
23 /**
24 * Optional name for this `ApolloClient` instance in the devtools. This is
25 * useful when you instantiate multiple clients and want to be able to
26 * identify them by name.
27 */
28 name?: string;
29}
30export interface ApolloClientOptions<TCacheShape> {
31 /**
32 * The URI of the GraphQL endpoint that Apollo Client will communicate with.
33 *
34 * One of `uri` or `link` is **required**. If you provide both, `link` takes precedence.
35 */
36 uri?: string | UriFunction;
37 credentials?: string;
38 /**
39 * An object representing headers to include in every HTTP request, such as `{Authorization: 'Bearer 1234'}`
40 *
41 * This value will be ignored when using the `link` option.
42 */
43 headers?: Record<string, string>;
44 /**
45 * 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/).
46 *
47 * One of `uri` or `link` is **required**. If you provide both, `link` takes precedence.
48 */
49 link?: ApolloLink;
50 /**
51 * 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.
52 *
53 * For more information, see [Configuring the cache](https://www.apollographql.com/docs/react/caching/cache-configuration/).
54 */
55 cache: ApolloCache<TCacheShape>;
56 /**
57 * The time interval (in milliseconds) before Apollo Client force-fetches queries after a server-side render.
58 *
59 * @defaultValue `0` (no delay)
60 */
61 ssrForceFetchDelay?: number;
62 /**
63 * 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.
64 *
65 * @defaultValue `false`
66 */
67 ssrMode?: boolean;
68 /**
69 * 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.
70 *
71 * The default value is `false` in production and `true` in development (if there is a `window` object).
72 * @deprecated Please use the `devtools.enabled` option.
73 */
74 connectToDevTools?: boolean;
75 /**
76 * 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.
77 *
78 * @defaultValue `true`
79 */
80 queryDeduplication?: boolean;
81 /**
82 * 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.
83 *
84 * See this [example object](https://www.apollographql.com/docs/react/api/core/ApolloClient#example-defaultoptions-object).
85 */
86 defaultOptions?: DefaultOptions;
87 defaultContext?: Partial<DefaultContext>;
88 /**
89 * If `true`, Apollo Client will assume results read from the cache are never mutated by application code, which enables substantial performance optimizations.
90 *
91 * @defaultValue `false`
92 */
93 assumeImmutableResults?: boolean;
94 resolvers?: Resolvers | Resolvers[];
95 typeDefs?: string | string[] | DocumentNode | DocumentNode[];
96 fragmentMatcher?: FragmentMatcher;
97 /**
98 * 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.
99 */
100 name?: string;
101 /**
102 * 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.
103 *
104 * 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.
105 */
106 version?: string;
107 documentTransform?: DocumentTransform;
108 /**
109 * Configuration used by the [Apollo Client Devtools extension](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) for this client.
110 *
111 * @since 3.11.0
112 */
113 devtools?: DevtoolsOptions;
114}
115import { mergeOptions } from "../utilities/index.js";
116import { getApolloClientMemoryInternals } from "../utilities/caching/getMemoryInternals.js";
117import type { WatchFragmentOptions, WatchFragmentResult } from "../cache/core/cache.js";
118export { mergeOptions };
119/**
120 * This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries
121 * and mutations) to a GraphQL spec-compliant server over an `ApolloLink` instance,
122 * receive results from the server and cache the results in a store. It also delivers updates
123 * to GraphQL queries through `Observable` instances.
124 */
125export declare class ApolloClient<TCacheShape> implements DataProxy {
126 link: ApolloLink;
127 cache: ApolloCache<TCacheShape>;
128 disableNetworkFetches: boolean;
129 version: string;
130 queryDeduplication: boolean;
131 defaultOptions: DefaultOptions;
132 readonly typeDefs: ApolloClientOptions<TCacheShape>["typeDefs"];
133 readonly devtoolsConfig: DevtoolsOptions;
134 private queryManager;
135 private devToolsHookCb?;
136 private resetStoreCallbacks;
137 private clearStoreCallbacks;
138 private localState;
139 /**
140 * Constructs an instance of `ApolloClient`.
141 *
142 * @example
143 * ```js
144 * import { ApolloClient, InMemoryCache } from '@apollo/client';
145 *
146 * const cache = new InMemoryCache();
147 *
148 * const client = new ApolloClient({
149 * // Provide required constructor fields
150 * cache: cache,
151 * uri: 'http://localhost:4000/',
152 *
153 * // Provide some optional constructor fields
154 * name: 'react-web-client',
155 * version: '1.3',
156 * queryDeduplication: false,
157 * defaultOptions: {
158 * watchQuery: {
159 * fetchPolicy: 'cache-and-network',
160 * },
161 * },
162 * });
163 * ```
164 */
165 constructor(options: ApolloClientOptions<TCacheShape>);
166 private connectToDevTools;
167 /**
168 * The `DocumentTransform` used to modify GraphQL documents before a request
169 * is made. If a custom `DocumentTransform` is not provided, this will be the
170 * default document transform.
171 */
172 get documentTransform(): DocumentTransform;
173 /**
174 * Call this method to terminate any active client processes, making it safe
175 * to dispose of this `ApolloClient` instance.
176 */
177 stop(): void;
178 /**
179 * This watches the cache store of the query according to the options specified and
180 * returns an `ObservableQuery`. We can subscribe to this `ObservableQuery` and
181 * receive updated results through an observer when the cache store changes.
182 *
183 * Note that this method is not an implementation of GraphQL subscriptions. Rather,
184 * it uses Apollo's store in order to reactively deliver updates to your query results.
185 *
186 * For example, suppose you call watchQuery on a GraphQL query that fetches a person's
187 * first and last name and this person has a particular object identifier, provided by
188 * dataIdFromObject. Later, a different query fetches that same person's
189 * first and last name and the first name has now changed. Then, any observers associated
190 * with the results of the first query will be updated with a new result object.
191 *
192 * Note that if the cache does not change, the subscriber will *not* be notified.
193 *
194 * See [here](https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3#.3mb0cbcmc) for
195 * a description of store reactivity.
196 */
197 watchQuery<T = any, TVariables extends OperationVariables = OperationVariables>(options: WatchQueryOptions<TVariables, T>): ObservableQuery<T, TVariables>;
198 /**
199 * This resolves a single query according to the options specified and
200 * returns a `Promise` which is either resolved with the resulting data
201 * or rejected with an error.
202 *
203 * @param options - An object of type `QueryOptions` that allows us to
204 * describe how this query should be treated e.g. whether it should hit the
205 * server at all or just resolve from the cache, etc.
206 */
207 query<T = any, TVariables extends OperationVariables = OperationVariables>(options: QueryOptions<TVariables, T>): Promise<ApolloQueryResult<T>>;
208 /**
209 * This resolves a single mutation according to the options specified and returns a
210 * Promise which is either resolved with the resulting data or rejected with an
211 * error. In some cases both `data` and `errors` might be undefined, for example
212 * when `errorPolicy` is set to `'ignore'`.
213 *
214 * It takes options as an object with the following keys and values:
215 */
216 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>>;
217 /**
218 * This subscribes to a graphql subscription according to the options specified and returns an
219 * `Observable` which either emits received data or an error.
220 */
221 subscribe<T = any, TVariables extends OperationVariables = OperationVariables>(options: SubscriptionOptions<TVariables, T>): Observable<FetchResult<T>>;
222 /**
223 * Tries to read some data from the store in the shape of the provided
224 * GraphQL query without making a network request. This method will start at
225 * the root query. To start at a specific id returned by `dataIdFromObject`
226 * use `readFragment`.
227 *
228 * @param optimistic - Set to `true` to allow `readQuery` to return
229 * optimistic results. Is `false` by default.
230 */
231 readQuery<T = any, TVariables = OperationVariables>(options: DataProxy.Query<TVariables, T>, optimistic?: boolean): T | null;
232 /**
233 * Watches the cache store of the fragment according to the options specified
234 * and returns an `Observable`. We can subscribe to this
235 * `Observable` and receive updated results through an
236 * observer when the cache store changes.
237 *
238 * You must pass in a GraphQL document with a single fragment or a document
239 * with multiple fragments that represent what you are reading. If you pass
240 * in a document with multiple fragments then you must also specify a
241 * `fragmentName`.
242 *
243 * @since 3.10.0
244 * @param options - An object of type `WatchFragmentOptions` that allows
245 * the cache to identify the fragment and optionally specify whether to react
246 * to optimistic updates.
247 */
248 watchFragment<TFragmentData = unknown, TVariables = OperationVariables>(options: WatchFragmentOptions<TFragmentData, TVariables>): Observable<WatchFragmentResult<TFragmentData>>;
249 /**
250 * Tries to read some data from the store in the shape of the provided
251 * GraphQL fragment without making a network request. This method will read a
252 * GraphQL fragment from any arbitrary id that is currently cached, unlike
253 * `readQuery` which will only read from the root query.
254 *
255 * You must pass in a GraphQL document with a single fragment or a document
256 * with multiple fragments that represent what you are reading. If you pass
257 * in a document with multiple fragments then you must also specify a
258 * `fragmentName`.
259 *
260 * @param optimistic - Set to `true` to allow `readFragment` to return
261 * optimistic results. Is `false` by default.
262 */
263 readFragment<T = any, TVariables = OperationVariables>(options: DataProxy.Fragment<TVariables, T>, optimistic?: boolean): T | null;
264 /**
265 * Writes some data in the shape of the provided GraphQL query directly to
266 * the store. This method will start at the root query. To start at a
267 * specific id returned by `dataIdFromObject` then use `writeFragment`.
268 */
269 writeQuery<TData = any, TVariables = OperationVariables>(options: DataProxy.WriteQueryOptions<TData, TVariables>): Reference | undefined;
270 /**
271 * Writes some data in the shape of the provided GraphQL fragment directly to
272 * the store. This method will write to a GraphQL fragment from any arbitrary
273 * id that is currently cached, unlike `writeQuery` which will only write
274 * from the root query.
275 *
276 * You must pass in a GraphQL document with a single fragment or a document
277 * with multiple fragments that represent what you are writing. If you pass
278 * in a document with multiple fragments then you must also specify a
279 * `fragmentName`.
280 */
281 writeFragment<TData = any, TVariables = OperationVariables>(options: DataProxy.WriteFragmentOptions<TData, TVariables>): Reference | undefined;
282 __actionHookForDevTools(cb: () => any): void;
283 __requestRaw(payload: GraphQLRequest): Observable<FormattedExecutionResult>;
284 /**
285 * Resets your entire store by clearing out your cache and then re-executing
286 * all of your active queries. This makes it so that you may guarantee that
287 * there is no data left in your store from a time before you called this
288 * method.
289 *
290 * `resetStore()` is useful when your user just logged out. You’ve removed the
291 * user session, and you now want to make sure that any references to data you
292 * might have fetched while the user session was active is gone.
293 *
294 * It is important to remember that `resetStore()` *will* refetch any active
295 * queries. This means that any components that might be mounted will execute
296 * their queries again using your network interface. If you do not want to
297 * re-execute any queries then you should make sure to stop watching any
298 * active queries.
299 */
300 resetStore(): Promise<ApolloQueryResult<any>[] | null>;
301 /**
302 * Remove all data from the store. Unlike `resetStore`, `clearStore` will
303 * not refetch any active queries.
304 */
305 clearStore(): Promise<any[]>;
306 /**
307 * Allows callbacks to be registered that are executed when the store is
308 * reset. `onResetStore` returns an unsubscribe function that can be used
309 * to remove registered callbacks.
310 */
311 onResetStore(cb: () => Promise<any>): () => void;
312 /**
313 * Allows callbacks to be registered that are executed when the store is
314 * cleared. `onClearStore` returns an unsubscribe function that can be used
315 * to remove registered callbacks.
316 */
317 onClearStore(cb: () => Promise<any>): () => void;
318 /**
319 * Refetches all of your active queries.
320 *
321 * `reFetchObservableQueries()` is useful if you want to bring the client back to proper state in case of a network outage
322 *
323 * It is important to remember that `reFetchObservableQueries()` *will* refetch any active
324 * queries. This means that any components that might be mounted will execute
325 * their queries again using your network interface. If you do not want to
326 * re-execute any queries then you should make sure to stop watching any
327 * active queries.
328 * Takes optional parameter `includeStandby` which will include queries in standby-mode when refetching.
329 */
330 reFetchObservableQueries(includeStandby?: boolean): Promise<ApolloQueryResult<any>[]>;
331 /**
332 * Refetches specified active queries. Similar to "reFetchObservableQueries()" but with a specific list of queries.
333 *
334 * `refetchQueries()` is useful for use cases to imperatively refresh a selection of queries.
335 *
336 * It is important to remember that `refetchQueries()` *will* refetch specified active
337 * queries. This means that any components that might be mounted will execute
338 * their queries again using your network interface. If you do not want to
339 * re-execute any queries then you should make sure to stop watching any
340 * active queries.
341 */
342 refetchQueries<TCache extends ApolloCache<any> = ApolloCache<TCacheShape>, TResult = Promise<ApolloQueryResult<any>>>(options: RefetchQueriesOptions<TCache, TResult>): RefetchQueriesResult<TResult>;
343 /**
344 * Get all currently active `ObservableQuery` objects, in a `Map` keyed by
345 * query ID strings.
346 *
347 * An "active" query is one that has observers and a `fetchPolicy` other than
348 * "standby" or "cache-only".
349 *
350 * You can include all `ObservableQuery` objects (including the inactive ones)
351 * by passing "all" instead of "active", or you can include just a subset of
352 * active queries by passing an array of query names or DocumentNode objects.
353 */
354 getObservableQueries(include?: RefetchQueriesInclude): Map<string, ObservableQuery<any>>;
355 /**
356 * Exposes the cache's complete state, in a serializable format for later restoration.
357 */
358 extract(optimistic?: boolean): TCacheShape;
359 /**
360 * Replaces existing state in the cache (if any) with the values expressed by
361 * `serializedState`.
362 *
363 * Called when hydrating a cache (server side rendering, or offline storage),
364 * and also (potentially) during hot reloads.
365 */
366 restore(serializedState: TCacheShape): ApolloCache<TCacheShape>;
367 /**
368 * Add additional local resolvers.
369 */
370 addResolvers(resolvers: Resolvers | Resolvers[]): void;
371 /**
372 * Set (override existing) local resolvers.
373 */
374 setResolvers(resolvers: Resolvers | Resolvers[]): void;
375 /**
376 * Get all registered local resolvers.
377 */
378 getResolvers(): Resolvers;
379 /**
380 * Set a custom local state fragment matcher.
381 */
382 setLocalStateFragmentMatcher(fragmentMatcher: FragmentMatcher): void;
383 /**
384 * Define a new ApolloLink (or link chain) that Apollo Client will use.
385 */
386 setLink(newLink: ApolloLink): void;
387 get defaultContext(): Partial<DefaultContext>;
388 /**
389 * @experimental
390 * This is not a stable API - it is used in development builds to expose
391 * information to the DevTools.
392 * Use at your own risk!
393 * For more details, see [Memory Management](https://www.apollographql.com/docs/react/caching/memory-management/#measuring-cache-usage)
394 *
395 * @example
396 * ```ts
397 * console.log(client.getMemoryInternals())
398 * ```
399 * Logs output in the following JSON format:
400 * @example
401 * ```json
402 *{
403 * limits: {
404 * parser: 1000,
405 * canonicalStringify: 1000,
406 * print: 2000,
407 * 'documentTransform.cache': 2000,
408 * 'queryManager.getDocumentInfo': 2000,
409 * 'PersistedQueryLink.persistedQueryHashes': 2000,
410 * 'fragmentRegistry.transform': 2000,
411 * 'fragmentRegistry.lookup': 1000,
412 * 'fragmentRegistry.findFragmentSpreads': 4000,
413 * 'cache.fragmentQueryDocuments': 1000,
414 * 'removeTypenameFromVariables.getVariableDefinitions': 2000,
415 * 'inMemoryCache.maybeBroadcastWatch': 5000,
416 * 'inMemoryCache.executeSelectionSet': 10000,
417 * 'inMemoryCache.executeSubSelectedArray': 5000
418 * },
419 * sizes: {
420 * parser: 26,
421 * canonicalStringify: 4,
422 * print: 14,
423 * addTypenameDocumentTransform: [
424 * {
425 * cache: 14,
426 * },
427 * ],
428 * queryManager: {
429 * getDocumentInfo: 14,
430 * documentTransforms: [
431 * {
432 * cache: 14,
433 * },
434 * {
435 * cache: 14,
436 * },
437 * ],
438 * },
439 * fragmentRegistry: {
440 * findFragmentSpreads: 34,
441 * lookup: 20,
442 * transform: 14,
443 * },
444 * cache: {
445 * fragmentQueryDocuments: 22,
446 * },
447 * inMemoryCache: {
448 * executeSelectionSet: 4345,
449 * executeSubSelectedArray: 1206,
450 * maybeBroadcastWatch: 32,
451 * },
452 * links: [
453 * {
454 * PersistedQueryLink: {
455 * persistedQueryHashes: 14,
456 * },
457 * },
458 * {
459 * removeTypenameFromVariables: {
460 * getVariableDefinitions: 14,
461 * },
462 * },
463 * ],
464 * },
465 * }
466 *```
467 */
468 getMemoryInternals?: typeof getApolloClientMemoryInternals;
469}
470//# sourceMappingURL=ApolloClient.d.ts.map
\No newline at end of file