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

utils.ts

617 lines16.0 KB

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,
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 * Defaults to `'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
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
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
131​
132export function isValidTimeout(value: unknown): value is number {
133 return typeof value === 'number' && value >= 0 && value !== Infinity
135​
136export function timeUntilStale(updatedAt: number, staleTime?: number): number {
137 return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)
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
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
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
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)
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 )
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
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
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
408​
409export function isPlainArray(value: unknown): value is Array<unknown> {
410 return Array.isArray(value) && value.length === Object.keys(value).length
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 ctor = o.constructor
421 if (ctor === undefined) {
422 return true
423 }
424​
425 // If has modified prototype
426 const prot = ctor.prototype
427 if (!hasObjectPrototype(prot)) {
428 return false
429 }
430​
431 // If constructor does not have an Object-specific method
432 if (!prot.hasOwnProperty('isPrototypeOf')) {
433 return false
434 }
435​
436 // Handles Objects created by Object.create(<arbitrary prototype>)
437 if (Object.getPrototypeOf(o) !== Object.prototype) {
438 return false
439 }
440​
441 // Most likely a plain Object
442 return true
444​
445function hasObjectPrototype(o: any): boolean {
446 return Object.prototype.toString.call(o) === '[object Object]'
448​
449export function sleep(timeout: number): Promise<void> {
450 return new Promise((resolve) => {
451 timeoutManager.setTimeout(resolve, timeout)
452 })
454​
455export function replaceData<
456 TData,
457 TOptions extends QueryOptions<any, any, any, any>,
458>(prevData: TData | undefined, data: TData, options: TOptions): TData {
459 if (typeof options.structuralSharing === 'function') {
460 return options.structuralSharing(prevData, data) as TData
461 } else if (options.structuralSharing !== false) {
462 if (process.env.NODE_ENV !== 'production') {
463 try {
464 return replaceEqualDeep(prevData, data)
465 } catch (error) {
466 console.error(
467 `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}`,
468 )
469​
470 // Prevent the replaceEqualDeep from being called again down below.
471 throw error
472 }
473 }
474 // Structurally share data between prev and new data if needed
475 return replaceEqualDeep(prevData, data)
476 }
477 return data
479​
480/**
481 * Intended to be passed as a query's `placeholderData` option, for example
482 * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new
483 * query key is fetching, it keeps displaying the previously fetched data until the new data arrives.
484 *
485 * @example
486 * ```ts
487 * new QueryObserver(queryClient, {
488 * queryKey: ['posts', page],
489 * queryFn: () => fetchPosts(page),
490 * placeholderData: keepPreviousData,
491 * })
492 * ```
493 */
494export function keepPreviousData<T>(
495 previousData: T | undefined,
496): T | undefined {
497 return previousData
499​
500export function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {
501 const newItems = [...items, item]
502 return max && newItems.length > max ? newItems.slice(1) : newItems
504​
505export function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {
506 const newItems = [item, ...items]
507 return max && newItems.length > max ? newItems.slice(0, -1) : newItems
509​
510/**
511 * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent
512 * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`,
513 * a query disabled via `skipToken` cannot be triggered with `refetch`.
514 *
515 * @example
516 * ```ts
517 * new QueryObserver(queryClient, {
518 * queryKey: ['post', postId],
519 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
520 * })
521 * ```
522 */
523export const skipToken = Symbol()
524/**
525 * The type of the {@link skipToken} sentinel value.
526 */
527export type SkipToken = typeof skipToken
528​
529export function ensureQueryFn<
530 TQueryFnData = unknown,
531 TQueryKey extends QueryKey = QueryKey,
532>(
533 options: {
534 queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken
535 queryHash?: string
536 },
537 fetchOptions?: FetchOptions<TQueryFnData>,
538): QueryFunction<TQueryFnData, TQueryKey> {
539 if (process.env.NODE_ENV !== 'production') {
540 if (options.queryFn === skipToken) {
541 console.error(
542 `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,
543 )
544 }
545 }
546​
547 // if we attempt to retry a fetch that was triggered from an initialPromise
548 // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise
549 // if an observer has already mounted, we will be able to retry with that queryFn
550 if (!options.queryFn && fetchOptions?.initialPromise) {
551 return () => fetchOptions.initialPromise!
552 }
553​
554 if (!options.queryFn || options.queryFn === skipToken) {
555 return () =>
556 Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))
557 }
558​
559 return options.queryFn
561​
562/**
563 * Resolves a `throwOnError` option to a boolean.
564 * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller,
565 * additional context such as the query or mutation) and its result is returned, allowing the throwing
566 * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined`
567 * resolves to `false`).
568 *
569 * @example
570 * ```ts
571 * const throwOnError =
572 * query.state.error && typeof options.throwOnError === 'function'
573 * ? shouldThrowError(options.throwOnError, [query.state.error, query])
574 * : options.throwOnError
575 * ```
576 */
577export function shouldThrowError<T extends (...args: Array<any>) => boolean>(
578 throwOnError: boolean | T | undefined,
579 params: Parameters<T>,
580): boolean {
581 // Allow throwOnError function to override throwing behavior on a per-error basis
582 if (typeof throwOnError === 'function') {
583 return throwOnError(...params)
584 }
585​
586 return !!throwOnError
588​
589export function addConsumeAwareSignal<T>(
590 object: T,
591 getSignal: () => AbortSignal,
592 onCancelled: VoidFunction,
593): T & { signal: AbortSignal } {
594 let consumed = false
595 let signal: AbortSignal | undefined
596​
597 Object.defineProperty(object, 'signal', {
598 enumerable: true,
599 get: () => {
600 signal ??= getSignal()
601 if (consumed) {
602 return signal
603 }
604​
605 consumed = true
606 if (signal.aborted) {
607 onCancelled()
608 } else {
609 signal.addEventListener('abort', onCancelled, { once: true })
610 }
611​
612 return signal
613 },
614 })
615​
616 return object as T & { signal: AbortSignal }