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