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