Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

queryCache.ts

403 lines12.4 KB

1import { hashKeyByOptions, matchQuery } from './utils'
2import { Query } from './query'
3import { notifyManager } from './notifyManager'
4import { Subscribable } from './subscribable'
5import type { QueryFilters } from './utils'
6import type { Action, QueryState } from './query'
7import type {
8 CacheKeyConfig,
9 DefaultError,
10 NotifyEvent,
11 QueryKey,
12 QueryOptions,
13 WithRequired,
14} from './types'
15import type { QueryClient } from './queryClient'
16import type { QueryObserver } from './queryObserver'
17​
18// TYPES
19​
20/**
21 * Global callbacks that fire for every query handled by a `QueryCache`, regardless of which
22 * component or observer triggered it. Unlike `QueryClient`'s `defaultOptions`, which a query can
23 * override, these callbacks are always called. Unlike `MutationCacheConfig`'s callbacks, these
24 * are fire-and-forget: their return value is not awaited before the query settles.
25 */
26export interface QueryCacheConfig {
27 /**
28 * Configures query key comparison and hashing globally.
29 * `equalityFn` compares individual values during partial matching and defaults to strict equality.
30 * `hashFn` takes precedence over a query's deprecated `queryKeyHashFn` option.
31 */
32 queryKey?: CacheKeyConfig<QueryKey>
33 /** Called when any query in the cache encounters an error. */
34 onError?: (
35 error: DefaultError,
36 query: Query<unknown, unknown, unknown>,
37 ) => void
38 /** Called when any query in the cache is successful. */
39 onSuccess?: (data: unknown, query: Query<unknown, unknown, unknown>) => void
40 /** Called when any query in the cache is settled, either successfully or with an error. */
41 onSettled?: (
42 data: unknown | undefined,
43 error: DefaultError | null,
44 query: Query<unknown, unknown, unknown>,
45 ) => void
47​
48interface NotifyEventQueryAdded extends NotifyEvent {
49 type: 'added'
50 query: Query<any, any, any, any>
52​
53interface NotifyEventQueryRemoved extends NotifyEvent {
54 type: 'removed'
55 query: Query<any, any, any, any>
57​
58interface NotifyEventQueryUpdated extends NotifyEvent {
59 type: 'updated'
60 query: Query<any, any, any, any>
61 action: Action<any, any>
63​
64interface NotifyEventQueryObserverAdded extends NotifyEvent {
65 type: 'observerAdded'
66 query: Query<any, any, any, any>
67 observer: QueryObserver<any, any, any, any, any>
69​
70interface NotifyEventQueryObserverRemoved extends NotifyEvent {
71 type: 'observerRemoved'
72 query: Query<any, any, any, any>
73 observer: QueryObserver<any, any, any, any, any>
75​
76interface NotifyEventQueryObserverResultsUpdated extends NotifyEvent {
77 type: 'observerResultsUpdated'
78 query: Query<any, any, any, any>
80​
81interface NotifyEventQueryObserverOptionsUpdated extends NotifyEvent {
82 type: 'observerOptionsUpdated'
83 query: Query<any, any, any, any>
84 observer: QueryObserver<any, any, any, any, any>
86​
87/**
88 * The event passed to a `QueryCache` subscriber. Fired whenever a query is added or removed from
89 * the cache, its state is updated (e.g. via `query.setState` or `queryClient.removeQueries`), or
90 * one of its observers is added, removed, or has its results or options updated.
91 */
92export type QueryCacheNotifyEvent =
93 | NotifyEventQueryAdded
94 | NotifyEventQueryRemoved
95 | NotifyEventQueryUpdated
96 | NotifyEventQueryObserverAdded
97 | NotifyEventQueryObserverRemoved
98 | NotifyEventQueryObserverResultsUpdated
99 | NotifyEventQueryObserverOptionsUpdated
100​
101type QueryCacheListener = (event: QueryCacheNotifyEvent) => void
102​
103/**
104 * The store a `QueryCache` keeps its queries in, keyed by query hash.
105 */
106export interface QueryStore {
107 /**
108 * Returns whether a query with the given hash is stored.
109 */
110 has: (queryHash: string) => boolean
111 /**
112 * Stores a query under its hash.
113 */
114 set: (queryHash: string, query: Query) => void
115 /**
116 * Returns the query with the given hash, if any.
117 */
118 get: (queryHash: string) => Query | undefined
119 /**
120 * Removes the query with the given hash.
121 */
122 delete: (queryHash: string) => void
123 /**
124 * Returns an iterator over all stored queries.
125 */
126 values: () => IterableIterator<Query>
128​
129// CLASS
130​
131/**
132 * The `QueryCache` is the storage mechanism for TanStack Query. It stores all the data, meta
133 * information, and state of the queries it contains.
134 *
135 * Normally, you will not interact with the `QueryCache` directly and instead use a `QueryClient`
136 * for a specific cache. You can subscribe to it (inherited from `Subscribable`) to be informed of
137 * safe/known updates to the cache, such as queries being added, removed, or updated β€” updates made
138 * outside of the cache's own tracked mechanisms (e.g. mutating a query's state object directly) do
139 * not notify subscribers.
140 * @example
141 * ```ts
142 * const unsubscribe = queryCache.subscribe((event) => {
143 * console.log(event.type, event.query)
144 * })
145 * ```
146 */
147export class QueryCache extends Subscribable<QueryCacheListener> {
148 #queries: QueryStore
149​
150 constructor(public config: QueryCacheConfig = {}) {
151 super()
152 this.#queries = new Map<string, Query>()
153 }
154​
155 /**
156 * Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or
157 * builds and adds a new one to the cache if none exists yet. Used by framework adapters and
158 * plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing
159 * the reactive `QueryObserver` machinery.
160 * @param client - The client the query belongs to, used to default its options.
161 * @param options - The query options, including the `queryKey`. A new query is created with the
162 * options defaulted by {@link QueryClient#defaultQueryOptions}.
163 * @param state - The initial state of a newly created query, e.g. when hydrating. Ignored if the
164 * query already exists.
165 * @returns The existing or newly created query.
166 * @example
167 * ```ts
168 * const queryCache = queryClient.getQueryCache()
169 *
170 * const query = queryCache.build(queryClient, {
171 * queryKey: ['posts'],
172 * queryFn: fetchPosts,
173 * })
174 * ```
175 */
176 build<
177 TQueryFnData = unknown,
178 TError = DefaultError,
179 TData = TQueryFnData,
180 TQueryKey extends QueryKey = QueryKey,
181 >(
182 client: QueryClient,
183 options: WithRequired<
184 QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
185 'queryKey'
186 >,
187 state?: QueryState<TData, TError>,
188 ): Query<TQueryFnData, TError, TData, TQueryKey> {
189 const queryKey = options.queryKey
190 const queryHash =
191 options.queryHash ??
192 hashKeyByOptions(queryKey, this.config.queryKey, options)
193 let query = this.get<TQueryFnData, TError, TData, TQueryKey>(queryHash)
194​
195 if (!query) {
196 query = new Query({
197 client,
198 queryKey,
199 queryHash,
200 options: client.defaultQueryOptions(options),
201 state,
202 defaultOptions: client.getQueryDefaults(queryKey),
203 })
204 this.add(query)
205 }
206​
207 return query
208 }
209​
210 /**
211 * Adds a query to the cache.
212 * @internal
213 * @param query - The query to add. If a query with the same hash is already cached, nothing
214 * happens.
215 */
216 add(query: Query<any, any, any, any>): void {
217 if (!this.#queries.has(query.queryHash)) {
218 this.#queries.set(query.queryHash, query)
219​
220 this.notify({
221 type: 'added',
222 query,
223 })
224 }
225 }
226​
227 /**
228 * Destroys the given `Query` and removes it from the cache, notifying subscribers with a
229 * `'removed'` event. A no-op if the query is no longer the one currently stored under its hash
230 * (e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror
231 * removals across `QueryCache` instances.
232 * @param query - The query to remove.
233 * @example
234 * ```ts
235 * const queryCache = queryClient.getQueryCache()
236 * const query = queryCache.find({ queryKey: ['posts'] })
237 *
238 * if (query) {
239 * queryCache.remove(query)
240 * }
241 * ```
242 */
243 remove(query: Query<any, any, any, any>): void {
244 const queryInMap = this.#queries.get(query.queryHash)
245​
246 if (queryInMap === query) {
247 query.destroy()
248 this.#queries.delete(query.queryHash)
249 this.notify({ type: 'removed', query })
250 }
251 }
252​
253 /**
254 * Removes all queries from the cache.
255 * @example
256 * ```ts
257 * const queryCache = queryClient.getQueryCache()
258 *
259 * queryCache.clear()
260 * ```
261 */
262 clear(): void {
263 notifyManager.batch(() => {
264 this.getAll().forEach((query) => {
265 this.remove(query)
266 })
267 })
268 }
269​
270 /**
271 * Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none
272 * exists. Unlike {@link QueryCache#find}, this looks up by the already-computed hash rather
273 * than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash
274 * to look up directly.
275 * @param queryHash - The hash of the query to look up.
276 * @returns The query stored under the hash, or `undefined`.
277 * @example
278 * ```ts
279 * const queryCache = queryClient.getQueryCache()
280 * const queryHash = hashKey(['posts'])
281 *
282 * const query = queryCache.get(queryHash)
283 * ```
284 */
285 get<
286 TQueryFnData = unknown,
287 TError = DefaultError,
288 TData = TQueryFnData,
289 TQueryKey extends QueryKey = QueryKey,
290 >(
291 queryHash: string,
292 ): Query<TQueryFnData, TError, TData, TQueryKey> | undefined {
293 return this.#queries.get(queryHash) as
294 | Query<TQueryFnData, TError, TData, TQueryKey>
295 | undefined
296 }
297​
298 /**
299 * Returns all queries within the cache.
300 * @returns Every query in the cache.
301 * @example
302 * ```ts
303 * const queryCache = queryClient.getQueryCache()
304 *
305 * const queries = queryCache.getAll()
306 * ```
307 */
308 getAll(): Array<Query> {
309 return [...this.#queries.values()]
310 }
311​
312 /**
313 * A slightly more advanced method that can be used to get an existing query instance from the
314 * cache. This instance not only contains all the state for the query, but all of the instances,
315 * and underlying guts of the query as well. If the query does not exist, `undefined` is
316 * returned.
317 *
318 * This is not typically needed for most applications, but can come in handy when needing more
319 * information about a query in rare scenarios (e.g. looking at `query.state.dataUpdatedAt` to
320 * decide whether a query is fresh enough to be used as an initial value).
321 * @param filters - The filters to match, including the required `queryKey`. `exact` defaults to
322 * `true`.
323 * @returns The first matching query, or `undefined`.
324 * @see {@link QueryCache#findAll}
325 * @example
326 * ```ts
327 * const queryCache = queryClient.getQueryCache()
328 *
329 * const query = queryCache.find({ queryKey: ['posts'] })
330 * ```
331 */
332 find<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData>(
333 filters: WithRequired<QueryFilters, 'queryKey'>,
334 ): Query<TQueryFnData, TError, TData> | undefined {
335 const defaultedFilters = { exact: true, ...filters }
336​
337 return this.getAll().find((query) =>
338 matchQuery(defaultedFilters, query, this.config.queryKey),
339 ) as Query<TQueryFnData, TError, TData> | undefined
340 }
341​
342 /**
343 * An even more advanced method that can be used to get existing query instances from the cache
344 * that partially match a query key. If no queries match, an empty array is returned.
345 *
346 * This is not typically needed for most applications, but can come in handy when needing more
347 * information about queries in rare scenarios.
348 * @param filters - The filters to match. Without filters, every query is returned.
349 * @returns The matching queries.
350 * @see {@link QueryCache#find}
351 * @example
352 * ```ts
353 * const queryCache = queryClient.getQueryCache()
354 *
355 * const queries = queryCache.findAll({ queryKey: ['posts'] })
356 * ```
357 */
358 findAll(filters: QueryFilters<any> = {}): Array<Query> {
359 const queries = this.getAll()
360 return Object.keys(filters).length > 0
361 ? queries.filter((query) =>
362 matchQuery(filters, query, this.config.queryKey),
363 )
364 : queries
365 }
366​
367 /**
368 * Notifies every cache listener of an event, in one batch.
369 * @internal
370 * @param event - The event passed to every listener.
371 */
372 notify(event: QueryCacheNotifyEvent): void {
373 notifyManager.batch(() => {
374 this.listeners.forEach((listener) => {
375 listener(event)
376 })
377 })
378 }
379​
380 /**
381 * Calls {@link Query#onFocus} on every cached query, in one batch.
382 * @internal
383 */
384 onFocus(): void {
385 notifyManager.batch(() => {
386 this.getAll().forEach((query) => {
387 query.onFocus()
388 })
389 })
390 }
391​
392 /**
393 * Calls {@link Query#onOnline} on every cached query, in one batch.
394 * @internal
395 */
396 onOnline(): void {
397 notifyManager.batch(() => {
398 this.getAll().forEach((query) => {
399 query.onOnline()
400 })
401 })
402 }