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