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

queryCache.ts

393 lines12.0 KB

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