Open History to see the last commit
1import type { Query } from './query'
2import type {
3 MutationFunction,
4 MutationKey,
5 MutationOptions,
6 QueryFunction,
7 QueryKey,
8 QueryKeyHashFunction,
9 QueryOptions,
10} from './types'
11β
12// TYPES
13β
14export interface QueryFilters {
15 /**
16 * Include or exclude active queries
17 */
18 active?: boolean
19 /**
20 * Match query key exactly
21 */
22 exact?: boolean
23 /**
24 * Include or exclude inactive queries
25 */
26 inactive?: 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?: QueryKey
35 /**
36 * Include or exclude stale queries
37 */
38 stale?: boolean
39 /**
40 * Include or exclude fetching queries
41 */
42 fetching?: boolean
43}
44β
45export type DataUpdateFunction<TInput, TOutput> = (input: TInput) => TOutput
46β
47export type Updater<TInput, TOutput> =
48 | TOutput
49 | DataUpdateFunction<TInput, TOutput>
50β
51// UTILS
52β
53export const isServer = typeof window === 'undefined'
54β
55export function noop(): undefined {
56 return undefined
57}
58β
59export function functionalUpdate<TInput, TOutput>(
60 updater: Updater<TInput, TOutput>,
61 input: TInput
62): TOutput {
63 return typeof updater === 'function'
64 ? (updater as DataUpdateFunction<TInput, TOutput>)(input)
65 : updater
66}
67β
68export function isValidTimeout(value: any): value is number {
69 return typeof value === 'number' && value >= 0 && value !== Infinity
70}
71β
72export function ensureArray<T>(value: T | T[]): T[] {
73 return Array.isArray(value) ? value : [value]
74}
75β
76export function difference<T>(array1: T[], array2: T[]): T[] {
77 return array1.filter(x => array2.indexOf(x) === -1)
78}
79β
80export function replaceAt<T>(array: T[], index: number, value: T): T[] {
81 const copy = array.slice(0)
82 copy[index] = value
83 return copy
84}
85β
86export function timeUntilStale(updatedAt: number, staleTime?: number): number {
87 return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)
88}
89β
90export function parseQueryArgs<TOptions extends QueryOptions<any, any, any>>(
91 arg1: QueryKey | TOptions,
92 arg2?: QueryFunction<any> | TOptions,
93 arg3?: TOptions
94): TOptions {
95 if (!isQueryKey(arg1)) {
96 return arg1 as TOptions
97 }
98β
99 if (typeof arg2 === 'function') {
100 return { ...arg3, queryKey: arg1, queryFn: arg2 } as TOptions
101 }
102β
103 return { ...arg2, queryKey: arg1 } as TOptions
104}
105β
106export function parseMutationArgs<
107 TOptions extends MutationOptions<any, any, any, any>
108>(
109 arg1: MutationKey | MutationFunction<any, any> | TOptions,
110 arg2?: MutationFunction<any, any> | TOptions,
111 arg3?: TOptions
112): TOptions {
113 if (isQueryKey(arg1)) {
114 if (typeof arg2 === 'function') {
115 return { ...arg3, mutationKey: arg1, mutationFn: arg2 } as TOptions
116 }
117 return { ...arg2, mutationKey: arg1 } as TOptions
118 }
119β
120 if (typeof arg1 === 'function') {
121 return { ...arg2, mutationFn: arg1 } as TOptions
122 }
123β
124 return { ...arg1 } as TOptions
125}
126β
127export function parseFilterArgs<
128 TFilters extends QueryFilters,
129 TOptions = unknown
130>(
131 arg1?: QueryKey | TFilters,
132 arg2?: TFilters | TOptions,
133 arg3?: TOptions
134): [TFilters, TOptions | undefined] {
135 return (isQueryKey(arg1)
136 ? [{ ...arg2, queryKey: arg1 }, arg3]
137 : [arg1 || {}, arg2]) as [TFilters, TOptions]
138}
139β
140export function matchQuery(
141 filters: QueryFilters,
142 query: Query<any, any>
143): boolean {
144 const {
145 active,
146 exact,
147 fetching,
148 inactive,
149 predicate,
150 queryKey,
151 stale,
152 } = filters
153β
154 if (isQueryKey(queryKey)) {
155 if (exact) {
156 const hashFn = getQueryKeyHashFn(query.options)
157 if (query.queryHash !== hashFn(queryKey)) {
158 return false
159 }
160 } else if (!partialMatchKey(query.queryKey, queryKey)) {
161 return false
162 }
163 }
164β
165 let isActive
166β
167 if (inactive === false || (active && !inactive)) {
168 isActive = true
169 } else if (active === false || (inactive && !active)) {
170 isActive = false
171 }
172β
173 if (typeof isActive === 'boolean' && query.isActive() !== isActive) {
174 return false
175 }
176β
177 if (typeof stale === 'boolean' && query.isStale() !== stale) {
178 return false
179 }
180β
181 if (typeof fetching === 'boolean' && query.isFetching() !== fetching) {
182 return false
183 }
184β
185 if (predicate && !predicate(query)) {
186 return false
187 }
188β
189 return true
190}
191β
192export function getQueryKeyHashFn(
193 options?: QueryOptions<any, any>
194): QueryKeyHashFunction {
195 return options?.queryKeyHashFn || hashQueryKey
196}
197β
198/**
199 * Default query keys hash function.
200 */
201export function hashQueryKey(queryKey: QueryKey): string {
202 return stableValueHash(queryKey)
203}
204β
205/**
206 * Hashes the value into a stable hash.
207 */
208export function stableValueHash(value: any): string {
209 return JSON.stringify(value, (_, val) =>
210 isPlainObject(val)
211 ? Object.keys(val)
212 .sort()
213 .reduce((result, key) => {
214 result[key] = val[key]
215 return result
216 }, {} as any)
217 : val
218 )
219}
220β
221/**
222 * Checks if key `b` partially matches with key `a`.
223 */
224export function partialMatchKey(
225 a: string | unknown[],
226 b: string | unknown[]
227): boolean {
228 return partialDeepEqual(ensureArray(a), ensureArray(b))
229}
230β
231/**
232 * Checks if `b` partially matches with `a`.
233 */
234export function partialDeepEqual(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 => !partialDeepEqual(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 = Array.isArray(a) && Array.isArray(b)
262β
263 if (array || (isPlainObject(a) && isPlainObject(b))) {
264 const aSize = array ? a.length : Object.keys(a).length
265 const bItems = array ? b : Object.keys(b)
266 const bSize = bItems.length
267 const copy: any = array ? [] : {}
268β
269 let equalItems = 0
270β
271 for (let i = 0; i < bSize; i++) {
272 const key = array ? i : bItems[i]
273 copy[key] = replaceEqualDeep(a[key], b[key])
274 if (copy[key] === a[key]) {
275 equalItems++
276 }
277 }
278β
279 return aSize === bSize && equalItems === aSize ? a : copy
280 }
281β
282 return b
283}
284β
285/**
286 * Shallow compare objects. Only works with objects that always have the same properties.
287 */
288export function shallowEqualObjects<T>(a: T, b: T): boolean {
289 if ((a && !b) || (b && !a)) {
290 return false
291 }
292β
293 for (const key in a) {
294 if (a[key] !== b[key]) {
295 return false
296 }
297 }
298β
299 return true
300}
301β
302// Copied from: https://github.com/jonschlinkert/is-plain-object
303export function isPlainObject(o: any): o is Object {
304 if (!hasObjectPrototype(o)) {
305 return false
306 }
307β
308 // If has modified constructor
309 const ctor = o.constructor
310 if (typeof ctor === 'undefined') {
311 return true
312 }
313β
314 // If has modified prototype
315 const prot = ctor.prototype
316 if (!hasObjectPrototype(prot)) {
317 return false
318 }
319β
320 // If constructor does not have an Object-specific method
321 if (!prot.hasOwnProperty('isPrototypeOf')) {
322 return false
323 }
324β
325 // Most likely a plain Object
326 return true
327}
328β
329function hasObjectPrototype(o: any): boolean {
330 return Object.prototype.toString.call(o) === '[object Object]'
331}
332β
333export function isQueryKey(value: any): value is QueryKey {
334 return typeof value === 'string' || Array.isArray(value)
335}
336β
337export function isError(value: any): value is Error {
338 return value instanceof Error
339}
340β
341export function sleep(timeout: number): Promise<void> {
342 return new Promise(resolve => {
343 setTimeout(resolve, timeout)
344 })
345}
346β
347/**
348 * Schedules a microtask.
349 * This can be useful to schedule state updates after rendering.
350 */
351export function scheduleMicrotask(callback: () => void): void {
352 Promise.resolve()
353 .then(callback)
354 .catch(error =>
355 setTimeout(() => {
356 throw error
357 })
358 )
359}