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