Open History to see the last commit
1import { timeoutManager } from './timeoutManager'
2import type {
3 DefaultError,
4 FetchStatus,
5 MutationKey,
6 MutationStatus,
7 QueryFunction,
8 QueryKey,
9 QueryOptions,
10} from './types'
11import type { Mutation } from './mutation'
12import type { FetchOptions, Query } from './query'
13β
14// TYPES
15β
16type DropLast<T extends ReadonlyArray<unknown>> = T extends readonly [
17 ...infer R,
18 unknown,
19]
20 ? readonly [...R]
21 : never
22β
23type TuplePrefixes<T extends ReadonlyArray<unknown>> = T extends readonly []
24 ? readonly []
25 : TuplePrefixes<DropLast<T>> | T
26β
27/**
28 * Filters used to select queries, for example in `queryClient.getQueriesData` or `queryClient.invalidateQueries`.
29 * All provided filters must match; filters that are left unspecified are ignored.
30 */
31export interface QueryFilters<TQueryKey extends QueryKey = QueryKey> {
32 /**
33 * Filter to active queries, inactive queries or all queries
34 *
35 * @defaultValue 'all'
36 */
37 type?: QueryTypeFilter
38 /**
39 * Match query key exactly
40 */
41 exact?: boolean
42 /**
43 * Include queries matching this predicate function
44 */
45 predicate?: (query: Query) => boolean
46 /**
47 * Include queries matching this query key
48 */
49 queryKey?: TQueryKey | TuplePrefixes<TQueryKey>
50 /**
51 * Include or exclude stale queries
52 */
53 stale?: boolean
54 /**
55 * Include queries matching their fetchStatus
56 */
57 fetchStatus?: FetchStatus
58}
59β
60/**
61 * Filters used to select mutations, for example in `mutationCache.findAll` or `queryClient.isMutating`.
62 * All provided filters must match; filters that are left unspecified are ignored.
63 */
64export interface MutationFilters<
65 TData = unknown,
66 TError = DefaultError,
67 TVariables = unknown,
68 TOnMutateResult = unknown,
69> {
70 /**
71 * Match mutation key exactly
72 */
73 exact?: boolean
74 /**
75 * Include mutations matching this predicate function
76 */
77 predicate?: (
78 mutation: Mutation<TData, TError, TVariables, TOnMutateResult>,
79 ) => boolean
80 /**
81 * Include mutations matching this mutation key
82 */
83 mutationKey?: TuplePrefixes<MutationKey>
84 /**
85 * Filter by mutation status
86 */
87 status?: MutationStatus
88}
89β
90/**
91 * Either a plain value of type `TOutput`, or a function that receives `TInput` and returns `TOutput`.
92 * Used for example by `setQueryData`-style updaters, which accept either the new data directly or a
93 * function that computes it from the previous data. See {@link functionalUpdate}.
94 *
95 * @example
96 * ```ts
97 * queryClient.setQueryData(['posts'], newPosts)
98 *
99 * // Or, using an updater function that receives the current data:
100 * queryClient.setQueryData(['posts'], (oldPosts) =>
101 * oldPosts ? [...oldPosts, newPost] : oldPosts,
102 * )
103 * ```
104 */
105export type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)
106β
107export type QueryTypeFilter = 'all' | 'active' | 'inactive'
108β
109// UTILS
110β
111/** @deprecated
112 * use `environmentManager.isServer()` instead.
113 */
114export const isServer = typeof window === 'undefined' || 'Deno' in globalThis
115β
116/**
117 * A function that does nothing.
118 */
119export function noop(): void
120export function noop(): undefined
121export function noop() {}
122β
123export function functionalUpdate<TInput, TOutput>(
124 updater: Updater<TInput, TOutput>,
125 input: TInput,
126): TOutput {
127 return typeof updater === 'function'
128 ? (updater as (_: TInput) => TOutput)(input)
129 : updater
130}
131β
132export function isValidTimeout(value: unknown): value is number {
133 return typeof value === 'number' && value >= 0 && value !== Infinity
134}
135β
136export function timeUntilStale(updatedAt: number, staleTime?: number): number {
137 return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)
138}
139β
140export function resolveQueryValue<
141 TValue,
142 TQueryFnData = unknown,
143 TError = DefaultError,
144 TData = TQueryFnData,
145 TQueryKey extends QueryKey = QueryKey,
146>(
147 value:
148 | undefined
149 | TValue
150 | ((query: Query<TQueryFnData, TError, TData, TQueryKey>) => TValue),
151 query: Query<TQueryFnData, TError, TData, TQueryKey>,
152): TValue | undefined {
153 return typeof value === 'function'
154 ? (
155 value as (
156 query: Query<TQueryFnData, TError, TData, TQueryKey>,
157 ) => TValue
158 )(query)
159 : value
160}
161β
162/**
163 * Checks whether a query matches the given {@link QueryFilters}.
164 * Every filter that is specified must match; filters that are left unspecified are ignored.
165 *
166 * @example
167 * ```ts
168 * const queryCache = queryClient.getQueryCache()
169 *
170 * const matchingQueries = queryCache
171 * .getAll()
172 * .filter((query) => matchQuery({ queryKey: ['posts'] }, query))
173 * ```
174 */
175export function matchQuery(
176 filters: QueryFilters,
177 query: Query<any, any, any, any>,
178): boolean {
179 const {
180 type = 'all',
181 exact,
182 fetchStatus,
183 predicate,
184 queryKey,
185 stale,
186 } = filters
187β
188 if (queryKey) {
189 if (exact) {
190 if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
191 return false
192 }
193 } else if (!partialMatchKey(query.queryKey, queryKey)) {
194 return false
195 }
196 }
197β
198 if (type !== 'all') {
199 const isActive = query.isActive()
200 if (type === 'active' && !isActive) {
201 return false
202 }
203 if (type === 'inactive' && isActive) {
204 return false
205 }
206 }
207β
208 if (typeof stale === 'boolean' && query.isStale() !== stale) {
209 return false
210 }
211β
212 if (fetchStatus && fetchStatus !== query.state.fetchStatus) {
213 return false
214 }
215β
216 if (predicate && !predicate(query)) {
217 return false
218 }
219β
220 return true
221}
222β
223/**
224 * Checks whether a mutation matches the given {@link MutationFilters}.
225 * Every filter that is specified must match; filters that are left unspecified are ignored.
226 * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match.
227 *
228 * @example
229 * ```ts
230 * const mutationCache = queryClient.getMutationCache()
231 *
232 * const matchingMutations = mutationCache
233 * .getAll()
234 * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation))
235 * ```
236 */
237export function matchMutation(
238 filters: MutationFilters,
239 mutation: Mutation<any, any>,
240): boolean {
241 const { exact, status, predicate, mutationKey } = filters
242 if (mutationKey) {
243 if (!mutation.options.mutationKey) {
244 return false
245 }
246 if (exact) {
247 if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
248 return false
249 }
250 } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
251 return false
252 }
253 }
254β
255 if (status && mutation.state.status !== status) {
256 return false
257 }
258β
259 if (predicate && !predicate(mutation)) {
260 return false
261 }
262β
263 return true
264}
265β
266export function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(
267 queryKey: TQueryKey,
268 options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,
269): string {
270 const hashFn = options?.queryKeyHashFn || hashKey
271 return hashFn(queryKey)
272}
273β
274/**
275 * Default query & mutation keys hash function.
276 * Hashes the value into a stable hash.
277 *
278 * @example
279 * ```ts
280 * // Object keys are sorted, so key order doesn't affect the hash:
281 * hashKey(['todos', { page: 1, filter: 'done' }]) // === '["todos",{"filter":"done","page":1}]'
282 * ```
283 */
284export function hashKey(queryKey: QueryKey | MutationKey): string {
285 return JSON.stringify(queryKey, (_, val) =>
286 isPlainObject(val)
287 ? Object.keys(val)
288 .sort()
289 .reduce((result, key) => {
290 result[key] = val[key]
291 return result
292 }, {} as any)
293 : val,
294 )
295}
296β
297/**
298 * Checks if key `b` partially matches with key `a`.
299 */
300export function partialMatchKey(a: QueryKey, b: QueryKey): boolean
301export function partialMatchKey(a: any, b: any): boolean {
302 if (a === b) {
303 return true
304 }
305β
306 if (typeof a !== typeof b) {
307 return false
308 }
309β
310 if (a && b && typeof a === 'object' && typeof b === 'object') {
311 if (Array.isArray(a) && Array.isArray(b)) {
312 if (b.length > a.length) return false
313 for (let i = 0; i < b.length; i++) {
314 if (!partialMatchKey(a[i], b[i])) {
315 return false
316 }
317 }
318 return true
319 }
320β
321 const bKeys = Object.keys(b)
322 for (const key of bKeys) {
323 if (!partialMatchKey(a[key], b[key])) {
324 return false
325 }
326 }
327 return true
328 }
329β
330 return false
331}
332β
333const hasOwn = Object.prototype.hasOwnProperty
334β
335/**
336 * This function returns `a` if `b` is deeply equal.
337 * If not, it will replace any deeply equal children of `b` with those of `a`.
338 * This can be used for structural sharing between JSON values for example.
339 */
340export function replaceEqualDeep<T>(a: unknown, b: T, depth?: number): T
341export function replaceEqualDeep(a: any, b: any, depth = 0): any {
342 if (a === b) {
343 return a
344 }
345β
346 if (depth > 500) return b
347β
348 const array = isPlainArray(a) && isPlainArray(b)
349β
350 if (!array && !(isPlainObject(a) && isPlainObject(b))) return b
351β
352 const aItems = array ? a : Object.keys(a)
353 const aSize = aItems.length
354 const bItems = array ? b : Object.keys(b)
355 const bSize = bItems.length
356 const copy: any = array ? new Array(bSize) : {}
357β
358 let equalItems = 0
359β
360 for (let i = 0; i < bSize; i++) {
361 const key: any = array ? i : bItems[i]
362 const aItem = a[key]
363 const bItem = b[key]
364β
365 if (aItem === bItem) {
366 copy[key] = aItem
367 if (array ? i < aSize : hasOwn.call(a, key)) equalItems++
368 continue
369 }
370β
371 if (
372 aItem === null ||
373 bItem === null ||
374 typeof aItem !== 'object' ||
375 typeof bItem !== 'object'
376 ) {
377 copy[key] = bItem
378 continue
379 }
380β
381 const v = replaceEqualDeep(aItem, bItem, depth + 1)
382 copy[key] = v
383 if (v === aItem) equalItems++
384 }
385β
386 return aSize === bSize && equalItems === aSize ? a : copy
387}
388β
389/**
390 * Shallow compare objects.
391 */
392export function shallowEqualObjects<T extends Record<string, any>>(
393 a: T,
394 b: T | undefined,
395): boolean {
396 if (!b || Object.keys(a).length !== Object.keys(b).length) {
397 return false
398 }
399β
400 for (const key in a) {
401 if (a[key] !== b[key]) {
402 return false
403 }
404 }
405β
406 return true
407}
408β
409export function isPlainArray(value: unknown): value is Array<unknown> {
410 return Array.isArray(value) && value.length === Object.keys(value).length
411}
412β
413// Copied from: https://github.com/jonschlinkert/is-plain-object
414export function isPlainObject(o: any): o is Record<PropertyKey, unknown> {
415 if (!hasObjectPrototype(o)) {
416 return false
417 }
418β
419 // If has no constructor
420 const objectPrototype = Object.getPrototypeOf(o)
421 const ctor = objectPrototype?.constructor
422 if (ctor === undefined) {
423 return true
424 }
425β
426 if (typeof ctor !== 'function') {
427 return false
428 }
429β
430 // If has modified prototype
431 const prot = ctor.prototype
432 if (!hasObjectPrototype(prot)) {
433 return false
434 }
435β
436 // If constructor does not have an Object-specific method
437 if (!prot.hasOwnProperty('isPrototypeOf')) {
438 return false
439 }
440β
441 // Handles Objects created by Object.create(<arbitrary prototype>)
442 if (objectPrototype !== Object.prototype) {
443 return false
444 }
445β
446 // Most likely a plain Object
447 return true
448}
449β
450function hasObjectPrototype(o: any): boolean {
451 return Object.prototype.toString.call(o) === '[object Object]'
452}
453β
454export function sleep(timeout: number): Promise<void> {
455 return new Promise((resolve) => {
456 timeoutManager.setTimeout(resolve, timeout)
457 })
458}
459β
460export function replaceData<
461 TData,
462 TOptions extends QueryOptions<any, any, any, any>,
463>(prevData: TData | undefined, data: TData, options: TOptions): TData {
464 if (typeof options.structuralSharing === 'function') {
465 return options.structuralSharing(prevData, data) as TData
466 } else if (options.structuralSharing !== false) {
467 if (process.env.NODE_ENV !== 'production') {
468 try {
469 return replaceEqualDeep(prevData, data)
470 } catch (error) {
471 console.error(
472 `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,
473 )
474β
475 // Prevent the replaceEqualDeep from being called again down below.
476 throw error
477 }
478 }
479 // Structurally share data between prev and new data if needed
480 return replaceEqualDeep(prevData, data)
481 }
482 return data
483}
484β
485/**
486 * Intended to be passed as a query's `placeholderData` option, for example
487 * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new
488 * query key is fetching, it keeps displaying the previously fetched data until the new data arrives.
489 *
490 * @example
491 * ```ts
492 * new QueryObserver(queryClient, {
493 * queryKey: ['posts', page],
494 * queryFn: () => fetchPosts(page),
495 * placeholderData: keepPreviousData,
496 * })
497 * ```
498 */
499export function keepPreviousData<T>(
500 previousData: T | undefined,
501): T | undefined {
502 return previousData
503}
504β
505export function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {
506 const newItems = [...items, item]
507 return max && newItems.length > max ? newItems.slice(1) : newItems
508}
509β
510export function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {
511 const newItems = [item, ...items]
512 return max && newItems.length > max ? newItems.slice(0, -1) : newItems
513}
514β
515/**
516 * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent
517 * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`,
518 * a query disabled via `skipToken` cannot be triggered with `refetch`.
519 *
520 * @example
521 * ```ts
522 * new QueryObserver(queryClient, {
523 * queryKey: ['post', postId],
524 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
525 * })
526 * ```
527 */
528export const skipToken = Symbol()
529/**
530 * The type of the {@link skipToken} sentinel value.
531 */
532export type SkipToken = typeof skipToken
533β
534export function ensureQueryFn<
535 TQueryFnData = unknown,
536 TQueryKey extends QueryKey = QueryKey,
537>(
538 options: {
539 queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken
540 queryHash?: string
541 },
542 fetchOptions?: FetchOptions<TQueryFnData>,
543): QueryFunction<TQueryFnData, TQueryKey> {
544 if (process.env.NODE_ENV !== 'production') {
545 if (options.queryFn === skipToken) {
546 console.error(
547 `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,
548 )
549 }
550 }
551β
552 // if we attempt to retry a fetch that was triggered from an initialPromise
553 // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise
554 // if an observer has already mounted, we will be able to retry with that queryFn
555 if (!options.queryFn && fetchOptions?.initialPromise) {
556 return () => fetchOptions.initialPromise!
557 }
558β
559 if (!options.queryFn || options.queryFn === skipToken) {
560 return () =>
561 Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))
562 }
563β
564 return options.queryFn
565}
566β
567/**
568 * Resolves a `throwOnError` option to a boolean.
569 * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller,
570 * additional context such as the query or mutation) and its result is returned, allowing the throwing
571 * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined`
572 * resolves to `false`).
573 *
574 * @example
575 * ```ts
576 * const throwOnError =
577 * query.state.error && typeof options.throwOnError === 'function'
578 * ? shouldThrowError(options.throwOnError, [query.state.error, query])
579 * : options.throwOnError
580 * ```
581 */
582export function shouldThrowError<T extends (...args: Array<any>) => boolean>(
583 throwOnError: boolean | T | undefined,
584 params: Parameters<T>,
585): boolean {
586 // Allow throwOnError function to override throwing behavior on a per-error basis
587 if (typeof throwOnError === 'function') {
588 return throwOnError(...params)
589 }
590β
591 return !!throwOnError
592}
593β
594export function addConsumeAwareSignal<T>(
595 object: T,
596 getSignal: () => AbortSignal,
597 onCancelled: VoidFunction,
598): T & { signal: AbortSignal } {
599 let consumed = false
600 let signal: AbortSignal | undefined
601β
602 Object.defineProperty(object, 'signal', {
603 enumerable: true,
604 get: () => {
605 signal ??= getSignal()
606 if (consumed) {
607 return signal
608 }
609β
610 consumed = true
611 if (signal.aborted) {
612 onCancelled()
613 } else {
614 signal.addEventListener('abort', onCancelled, { once: true })
615 }
616β
617 return signal
618 },
619 })
620β
621 return object as T & { signal: AbortSignal }
622}