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