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

utils.ts

467 lines11.6 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 const isServer = typeof window === 'undefined' || 'Deno' in globalThis
90​
91export function noop(): void
92export function noop(): undefined
93export function noop() {}
94​
95export function functionalUpdate<TInput, TOutput>(
96 updater: Updater<TInput, TOutput>,
97 input: TInput,
98): TOutput {
99 return typeof updater === 'function'
100 ? (updater as (_: TInput) => TOutput)(input)
101 : updater
103​
104export function isValidTimeout(value: unknown): value is number {
105 return typeof value === 'number' && value >= 0 && value !== Infinity
107​
108export function timeUntilStale(updatedAt: number, staleTime?: number): number {
109 return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)
111​
112export function resolveStaleTime<
113 TQueryFnData = unknown,
114 TError = DefaultError,
115 TData = TQueryFnData,
116 TQueryKey extends QueryKey = QueryKey,
117>(
118 staleTime:
119 | undefined
120 | StaleTimeFunction<TQueryFnData, TError, TData, TQueryKey>,
121 query: Query<TQueryFnData, TError, TData, TQueryKey>,
122): StaleTime | undefined {
123 return typeof staleTime === 'function' ? staleTime(query) : staleTime
125​
126export function resolveEnabled<
127 TQueryFnData = unknown,
128 TError = DefaultError,
129 TData = TQueryFnData,
130 TQueryKey extends QueryKey = QueryKey,
131>(
132 enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,
133 query: Query<TQueryFnData, TError, TData, TQueryKey>,
134): boolean | undefined {
135 return typeof enabled === 'function' ? enabled(query) : enabled
137​
138export function matchQuery(
139 filters: QueryFilters,
140 query: Query<any, any, any, any>,
141): boolean {
142 const {
143 type = 'all',
144 exact,
145 fetchStatus,
146 predicate,
147 queryKey,
148 stale,
149 } = filters
150​
151 if (queryKey) {
152 if (exact) {
153 if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
154 return false
155 }
156 } else if (!partialMatchKey(query.queryKey, queryKey)) {
157 return false
158 }
159 }
160​
161 if (type !== 'all') {
162 const isActive = query.isActive()
163 if (type === 'active' && !isActive) {
164 return false
165 }
166 if (type === 'inactive' && isActive) {
167 return false
168 }
169 }
170​
171 if (typeof stale === 'boolean' && query.isStale() !== stale) {
172 return false
173 }
174​
175 if (fetchStatus && fetchStatus !== query.state.fetchStatus) {
176 return false
177 }
178​
179 if (predicate && !predicate(query)) {
180 return false
181 }
182​
183 return true
185​
186export function matchMutation(
187 filters: MutationFilters,
188 mutation: Mutation<any, any>,
189): boolean {
190 const { exact, status, predicate, mutationKey } = filters
191 if (mutationKey) {
192 if (!mutation.options.mutationKey) {
193 return false
194 }
195 if (exact) {
196 if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
197 return false
198 }
199 } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
200 return false
201 }
202 }
203​
204 if (status && mutation.state.status !== status) {
205 return false
206 }
207​
208 if (predicate && !predicate(mutation)) {
209 return false
210 }
211​
212 return true
214​
215export function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(
216 queryKey: TQueryKey,
217 options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,
218): string {
219 const hashFn = options?.queryKeyHashFn || hashKey
220 return hashFn(queryKey)
222​
223/**
224 * Default query & mutation keys hash function.
225 * Hashes the value into a stable hash.
226 */
227export function hashKey(queryKey: QueryKey | MutationKey): string {
228 return JSON.stringify(queryKey, (_, val) =>
229 isPlainObject(val)
230 ? Object.keys(val)
231 .sort()
232 .reduce((result, key) => {
233 result[key] = val[key]
234 return result
235 }, {} as any)
236 : val,
237 )
239​
240/**
241 * Checks if key `b` partially matches with key `a`.
242 */
243export function partialMatchKey(a: QueryKey, b: QueryKey): boolean
244export function partialMatchKey(a: any, b: any): boolean {
245 if (a === b) {
246 return true
247 }
248​
249 if (typeof a !== typeof b) {
250 return false
251 }
252​
253 if (a && b && typeof a === 'object' && typeof b === 'object') {
254 return Object.keys(b).every((key) => partialMatchKey(a[key], b[key]))
255 }
256​
257 return false
259​
260const hasOwn = Object.prototype.hasOwnProperty
261​
262/**
263 * This function returns `a` if `b` is deeply equal.
264 * If not, it will replace any deeply equal children of `b` with those of `a`.
265 * This can be used for structural sharing between JSON values for example.
266 */
267export function replaceEqualDeep<T>(a: unknown, b: T): T
268export function replaceEqualDeep(a: any, b: any): any {
269 if (a === b) {
270 return a
271 }
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)
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