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