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

utils.ts

497 lines12.2 KB

1import { timeoutManager } from './timeoutManager'
2import type {
3 DefaultError,
4 Enabled,
5 FetchStatus,
6 MutationKey,
7 MutationStatus,
8 QueryFunction,
9 QueryKey,
10 QueryOptions,
11 StaleTime,
12 StaleTimeFunction,
13} from './types'
14import type { Mutation } from './mutation'
15import type { FetchOptions, Query } from './query'
16​
17// TYPES
18​
19type DropLast<T extends ReadonlyArray<unknown>> = T extends readonly [
20 ...infer R,
21 unknown,
23 ? readonly [...R]
24 : never
25​
26type TuplePrefixes<T extends ReadonlyArray<unknown>> = T extends readonly []
27 ? readonly []
28 : TuplePrefixes<DropLast<T>> | T
29​
30export interface QueryFilters<TQueryKey extends QueryKey = QueryKey> {
31 /**
32 * Filter to active queries, inactive queries or all queries
33 */
34 type?: QueryTypeFilter
35 /**
36 * Match query key exactly
37 */
38 exact?: boolean
39 /**
40 * Include queries matching this predicate function
41 */
42 predicate?: (query: Query) => boolean
43 /**
44 * Include queries matching this query key
45 */
46 queryKey?: TQueryKey | TuplePrefixes<TQueryKey>
47 /**
48 * Include or exclude stale queries
49 */
50 stale?: boolean
51 /**
52 * Include queries matching their fetchStatus
53 */
54 fetchStatus?: FetchStatus
56​
57export interface MutationFilters<
58 TData = unknown,
59 TError = DefaultError,
60 TVariables = unknown,
61 TOnMutateResult = unknown,
62> {
63 /**
64 * Match mutation key exactly
65 */
66 exact?: boolean
67 /**
68 * Include mutations matching this predicate function
69 */
70 predicate?: (
71 mutation: Mutation<TData, TError, TVariables, TOnMutateResult>,
72 ) => boolean
73 /**
74 * Include mutations matching this mutation key
75 */
76 mutationKey?: TuplePrefixes<MutationKey>
77 /**
78 * Filter by mutation status
79 */
80 status?: MutationStatus
82​
83export type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)
84​
85export type QueryTypeFilter = 'all' | 'active' | 'inactive'
86​
87// UTILS
88​
89export function noop(): void
90export function noop(): undefined
91export function noop() {}
92​
93export function functionalUpdate<TInput, TOutput>(
94 updater: Updater<TInput, TOutput>,
95 input: TInput,
96): TOutput {
97 return typeof updater === 'function'
98 ? (updater as (_: TInput) => TOutput)(input)
99 : updater
101​
102export function isValidTimeout(value: unknown): value is number {
103 return typeof value === 'number' && value >= 0 && value !== Infinity
105​
106export function timeUntilStale(updatedAt: number, staleTime?: number): number {
107 return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)
109​
110export function resolveStaleTime<
111 TQueryFnData = unknown,
112 TError = DefaultError,
113 TData = TQueryFnData,
114 TQueryKey extends QueryKey = QueryKey,
115>(
116 staleTime:
117 | undefined
118 | StaleTimeFunction<TQueryFnData, TError, TData, TQueryKey>,
119 query: Query<TQueryFnData, TError, TData, TQueryKey>,
120): StaleTime | undefined {
121 return typeof staleTime === 'function' ? staleTime(query) : staleTime
123​
124export function resolveEnabled<
125 TQueryFnData = unknown,
126 TError = DefaultError,
127 TData = TQueryFnData,
128 TQueryKey extends QueryKey = QueryKey,
129>(
130 enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,
131 query: Query<TQueryFnData, TError, TData, TQueryKey>,
132): boolean | undefined {
133 return typeof enabled === 'function' ? enabled(query) : enabled
135​
136export function matchQuery(
137 filters: QueryFilters,
138 query: Query<any, any, any, any>,
139): boolean {
140 const {
141 type = 'all',
142 exact,
143 fetchStatus,
144 predicate,
145 queryKey,
146 stale,
147 } = filters
148​
149 if (queryKey) {
150 if (exact) {
151 if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
152 return false
153 }
154 } else if (!partialMatchKey(query.queryKey, queryKey)) {
155 return false
156 }
157 }
158​
159 if (type !== 'all') {
160 const isActive = query.isActive()
161 if (type === 'active' && !isActive) {
162 return false
163 }
164 if (type === 'inactive' && isActive) {
165 return false
166 }
167 }
168​
169 if (typeof stale === 'boolean' && query.isStale() !== stale) {
170 return false
171 }
172​
173 if (fetchStatus && fetchStatus !== query.state.fetchStatus) {
174 return false
175 }
176​
177 if (predicate && !predicate(query)) {
178 return false
179 }
180​
181 return true
183​
184export function matchMutation(
185 filters: MutationFilters,
186 mutation: Mutation<any, any>,
187): boolean {
188 const { exact, status, predicate, mutationKey } = filters
189 if (mutationKey) {
190 if (!mutation.options.mutationKey) {
191 return false
192 }
193 if (exact) {
194 if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
195 return false
196 }
197 } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
198 return false
199 }
200 }
201​
202 if (status && mutation.state.status !== status) {
203 return false
204 }
205​
206 if (predicate && !predicate(mutation)) {
207 return false
208 }
209​
210 return true
212​
213export function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(
214 queryKey: TQueryKey,
215 options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,
216): string {
217 const hashFn = options?.queryKeyHashFn || hashKey
218 return hashFn(queryKey)
220​
221/**
222 * Default query & mutation keys hash function.
223 * Hashes the value into a stable hash.
224 */
225export function hashKey(queryKey: QueryKey | MutationKey): string {
226 return JSON.stringify(queryKey, (_, val) =>
227 isPlainObject(val)
228 ? Object.keys(val)
229 .sort()
230 .reduce((result, key) => {
231 result[key] = val[key]
232 return result
233 }, {} as any)
234 : val,
235 )
237​
238/**
239 * Checks if key `b` partially matches with key `a`.
240 */
241export function partialMatchKey(a: QueryKey, b: QueryKey): boolean
242export function partialMatchKey(a: any, b: any): boolean {
243 if (a === b) {
244 return true
245 }
246​
247 if (typeof a !== typeof b) {
248 return false
249 }
250​
251 if (a && b && typeof a === 'object' && typeof b === 'object') {
252 return Object.keys(b).every((key) => partialMatchKey(a[key], b[key]))
253 }
254​
255 return false
257​
258const hasOwn = Object.prototype.hasOwnProperty
259​
260/**
261 * This function returns `a` if `b` is deeply equal.
262 * If not, it will replace any deeply equal children of `b` with those of `a`.
263 * This can be used for structural sharing between JSON values for example.
264 */
265export function replaceEqualDeep<T>(a: unknown, b: T, depth?: number): T
266export function replaceEqualDeep(a: any, b: any, depth = 0): any {
267 if (a === b) {
268 return a
269 }
270​
271 if (depth > 500) return b
272​
273 const array = isPlainArray(a) && isPlainArray(b)
274​
275 if (!array && !(isPlainObject(a) && isPlainObject(b))) return b
276​
277 const aItems = array ? a : Object.keys(a)
278 const aSize = aItems.length
279 const bItems = array ? b : Object.keys(b)
280 const bSize = bItems.length
281 const copy: any = array ? new Array(bSize) : {}
282​
283 let equalItems = 0
284​
285 for (let i = 0; i < bSize; i++) {
286 const key: any = array ? i : bItems[i]
287 const aItem = a[key]
288 const bItem = b[key]
289​
290 if (aItem === bItem) {
291 copy[key] = aItem
292 if (array ? i < aSize : hasOwn.call(a, key)) equalItems++
293 continue
294 }
295​
296 if (
297 aItem === null ||
298 bItem === null ||
299 typeof aItem !== 'object' ||
300 typeof bItem !== 'object'
301 ) {
302 copy[key] = bItem
303 continue
304 }
305​
306 const v = replaceEqualDeep(aItem, bItem, depth + 1)
307 copy[key] = v
308 if (v === aItem) equalItems++
309 }
310​
311 return aSize === bSize && equalItems === aSize ? a : copy
313​
314/**
315 * Shallow compare objects.
316 */
317export function shallowEqualObjects<T extends Record<string, any>>(
318 a: T,
319 b: T | undefined,
320): boolean {
321 if (!b || Object.keys(a).length !== Object.keys(b).length) {
322 return false
323 }
324​
325 for (const key in a) {
326 if (a[key] !== b[key]) {
327 return false
328 }
329 }
330​
331 return true
333​
334export function isPlainArray(value: unknown): value is Array<unknown> {
335 return Array.isArray(value) && value.length === Object.keys(value).length
337​
338// Copied from: https://github.com/jonschlinkert/is-plain-object
339export function isPlainObject(o: any): o is Record<PropertyKey, unknown> {
340 if (!hasObjectPrototype(o)) {
341 return false
342 }
343​
344 // If has no constructor
345 const ctor = o.constructor
346 if (ctor === undefined) {
347 return true
348 }
349​
350 // If has modified prototype
351 const prot = ctor.prototype
352 if (!hasObjectPrototype(prot)) {
353 return false
354 }
355​
356 // If constructor does not have an Object-specific method
357 if (!prot.hasOwnProperty('isPrototypeOf')) {
358 return false
359 }
360​
361 // Handles Objects created by Object.create(<arbitrary prototype>)
362 if (Object.getPrototypeOf(o) !== Object.prototype) {
363 return false
364 }
365​
366 // Most likely a plain Object
367 return true
369​
370function hasObjectPrototype(o: any): boolean {
371 return Object.prototype.toString.call(o) === '[object Object]'
373​
374export function sleep(timeout: number): Promise<void> {
375 return new Promise((resolve) => {
376 timeoutManager.setTimeout(resolve, timeout)
377 })
379​
380export function replaceData<
381 TData,
382 TOptions extends QueryOptions<any, any, any, any>,
383>(prevData: TData | undefined, data: TData, options: TOptions): TData {
384 if (typeof options.structuralSharing === 'function') {
385 return options.structuralSharing(prevData, data) as TData
386 } else if (options.structuralSharing !== false) {
387 if (process.env.NODE_ENV !== 'production') {
388 try {
389 return replaceEqualDeep(prevData, data)
390 } catch (error) {
391 console.error(
392 `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}`,
393 )
394​
395 // Prevent the replaceEqualDeep from being called again down below.
396 throw error
397 }
398 }
399 // Structurally share data between prev and new data if needed
400 return replaceEqualDeep(prevData, data)
401 }
402 return data
404​
405export function keepPreviousData<T>(
406 previousData: T | undefined,
407): T | undefined {
408 return previousData
410​
411export function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {
412 const newItems = [...items, item]
413 return max && newItems.length > max ? newItems.slice(1) : newItems
415​
416export function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {
417 const newItems = [item, ...items]
418 return max && newItems.length > max ? newItems.slice(0, -1) : newItems
420​
421export const skipToken = Symbol()
422export type SkipToken = typeof skipToken
423​
424export function ensureQueryFn<
425 TQueryFnData = unknown,
426 TQueryKey extends QueryKey = QueryKey,
427>(
428 options: {
429 queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken
430 queryHash?: string
431 },
432 fetchOptions?: FetchOptions<TQueryFnData>,
433): QueryFunction<TQueryFnData, TQueryKey> {
434 if (process.env.NODE_ENV !== 'production') {
435 if (options.queryFn === skipToken) {
436 console.error(
437 `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,
438 )
439 }
440 }
441​
442 // if we attempt to retry a fetch that was triggered from an initialPromise
443 // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise
444 // if an observer has already mounted, we will be able to retry with that queryFn
445 if (!options.queryFn && fetchOptions?.initialPromise) {
446 return () => fetchOptions.initialPromise!
447 }
448​
449 if (!options.queryFn || options.queryFn === skipToken) {
450 return () =>
451 Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))
452 }
453​
454 return options.queryFn
456​
457export function shouldThrowError<T extends (...args: Array<any>) => boolean>(
458 throwOnError: boolean | T | undefined,
459 params: Parameters<T>,
460): boolean {
461 // Allow throwOnError function to override throwing behavior on a per-error basis
462 if (typeof throwOnError === 'function') {
463 return throwOnError(...params)
464 }
465​
466 return !!throwOnError
468​
469export function addConsumeAwareSignal<T>(
470 object: T,
471 getSignal: () => AbortSignal,
472 onCancelled: VoidFunction,
473): T & { signal: AbortSignal } {
474 let consumed = false
475 let signal: AbortSignal | undefined
476​
477 Object.defineProperty(object, 'signal', {
478 enumerable: true,
479 get: () => {
480 signal ??= getSignal()
481 if (consumed) {
482 return signal
483 }
484​
485 consumed = true
486 if (signal.aborted) {
487 onCancelled()
488 } else {
489 signal.addEventListener('abort', onCancelled, { once: true })
490 }
491​
492 return signal
493 },
494 })
495​
496 return object as T & { signal: AbortSignal }