Open History to see the last commit
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,
22]
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
55}
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
81}
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
102}
103β
104export function isValidTimeout(value: unknown): value is number {
105 return typeof value === 'number' && value >= 0 && value !== Infinity
106}
107β
108export function timeUntilStale(updatedAt: number, staleTime?: number): number {
109 return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)
110}
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
124}
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
136}
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
184}
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
213}
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)
221}
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 )
238}
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
258}
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, depth?: number): T
268export function replaceEqualDeep(a: any, b: any, depth = 0): any {
269 if (a === b) {
270 return a
271 }
272β
273 if (depth > 500) return b
274β
275 const array = isPlainArray(a) && isPlainArray(b)
276β
277 if (!array && !(isPlainObject(a) && isPlainObject(b))) return b
278β
279 const aItems = array ? a : Object.keys(a)
280 const aSize = aItems.length
281 const bItems = array ? b : Object.keys(b)
282 const bSize = bItems.length
283 const copy: any = array ? new Array(bSize) : {}
284β
285 let equalItems = 0
286β
287 for (let i = 0; i < bSize; i++) {
288 const key: any = array ? i : bItems[i]
289 const aItem = a[key]
290 const bItem = b[key]
291β
292 if (aItem === bItem) {
293 copy[key] = aItem
294 if (array ? i < aSize : hasOwn.call(a, key)) equalItems++
295 continue
296 }
297β
298 if (
299 aItem === null ||
300 bItem === null ||
301 typeof aItem !== 'object' ||
302 typeof bItem !== 'object'
303 ) {
304 copy[key] = bItem
305 continue
306 }
307β
308 const v = replaceEqualDeep(aItem, bItem, depth + 1)
309 copy[key] = v
310 if (v === aItem) equalItems++
311 }
312β
313 return aSize === bSize && equalItems === aSize ? a : copy
314}
315β
316/**
317 * Shallow compare objects.
318 */
319export function shallowEqualObjects<T extends Record<string, any>>(
320 a: T,
321 b: T | undefined,
322): boolean {
323 if (!b || Object.keys(a).length !== Object.keys(b).length) {
324 return false
325 }
326β
327 for (const key in a) {
328 if (a[key] !== b[key]) {
329 return false
330 }
331 }
332β
333 return true
334}
335β
336export function isPlainArray(value: unknown): value is Array<unknown> {
337 return Array.isArray(value) && value.length === Object.keys(value).length
338}
339β
340// Copied from: https://github.com/jonschlinkert/is-plain-object
341export function isPlainObject(o: any): o is Record<PropertyKey, unknown> {
342 if (!hasObjectPrototype(o)) {
343 return false
344 }
345β
346 // If has no constructor
347 const ctor = o.constructor
348 if (ctor === undefined) {
349 return true
350 }
351β
352 // If has modified prototype
353 const prot = ctor.prototype
354 if (!hasObjectPrototype(prot)) {
355 return false
356 }
357β
358 // If constructor does not have an Object-specific method
359 if (!prot.hasOwnProperty('isPrototypeOf')) {
360 return false
361 }
362β
363 // Handles Objects created by Object.create(<arbitrary prototype>)
364 if (Object.getPrototypeOf(o) !== Object.prototype) {
365 return false
366 }
367β
368 // Most likely a plain Object
369 return true
370}
371β
372function hasObjectPrototype(o: any): boolean {
373 return Object.prototype.toString.call(o) === '[object Object]'
374}
375β
376export function sleep(timeout: number): Promise<void> {
377 return new Promise((resolve) => {
378 timeoutManager.setTimeout(resolve, timeout)
379 })
380}
381β
382export function replaceData<
383 TData,
384 TOptions extends QueryOptions<any, any, any, any>,
385>(prevData: TData | undefined, data: TData, options: TOptions): TData {
386 if (typeof options.structuralSharing === 'function') {
387 return options.structuralSharing(prevData, data) as TData
388 } else if (options.structuralSharing !== false) {
389 if (process.env.NODE_ENV !== 'production') {
390 try {
391 return replaceEqualDeep(prevData, data)
392 } catch (error) {
393 console.error(
394 `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}`,
395 )
396β
397 // Prevent the replaceEqualDeep from being called again down below.
398 throw error
399 }
400 }
401 // Structurally share data between prev and new data if needed
402 return replaceEqualDeep(prevData, data)
403 }
404 return data
405}
406β
407export function keepPreviousData<T>(
408 previousData: T | undefined,
409): T | undefined {
410 return previousData
411}
412β
413export function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {
414 const newItems = [...items, item]
415 return max && newItems.length > max ? newItems.slice(1) : newItems
416}
417β
418export function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {
419 const newItems = [item, ...items]
420 return max && newItems.length > max ? newItems.slice(0, -1) : newItems
421}
422β
423export const skipToken = Symbol()
424export type SkipToken = typeof skipToken
425β
426export function ensureQueryFn<
427 TQueryFnData = unknown,
428 TQueryKey extends QueryKey = QueryKey,
429>(
430 options: {
431 queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken
432 queryHash?: string
433 },
434 fetchOptions?: FetchOptions<TQueryFnData>,
435): QueryFunction<TQueryFnData, TQueryKey> {
436 if (process.env.NODE_ENV !== 'production') {
437 if (options.queryFn === skipToken) {
438 console.error(
439 `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,
440 )
441 }
442 }
443β
444 // if we attempt to retry a fetch that was triggered from an initialPromise
445 // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise
446 // if an observer has already mounted, we will be able to retry with that queryFn
447 if (!options.queryFn && fetchOptions?.initialPromise) {
448 return () => fetchOptions.initialPromise!
449 }
450β
451 if (!options.queryFn || options.queryFn === skipToken) {
452 return () =>
453 Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))
454 }
455β
456 return options.queryFn
457}
458β
459export function shouldThrowError<T extends (...args: Array<any>) => boolean>(
460 throwOnError: boolean | T | undefined,
461 params: Parameters<T>,
462): boolean {
463 // Allow throwOnError function to override throwing behavior on a per-error basis
464 if (typeof throwOnError === 'function') {
465 return throwOnError(...params)
466 }
467β
468 return !!throwOnError
469}
470β
471export function addConsumeAwareSignal<T>(
472 object: T,
473 getSignal: () => AbortSignal,
474 onCancelled: VoidFunction,
475): T & { signal: AbortSignal } {
476 let consumed = false
477 let signal: AbortSignal | undefined
478β
479 Object.defineProperty(object, 'signal', {
480 enumerable: true,
481 get: () => {
482 signal ??= getSignal()
483 if (consumed) {
484 return signal
485 }
486β
487 consumed = true
488 if (signal.aborted) {
489 onCancelled()
490 } else {
491 signal.addEventListener('abort', onCancelled, { once: true })
492 }
493β
494 return signal
495 },
496 })
497β
498 return object as T & { signal: AbortSignal }
499}