UNPKG

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