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