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