Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

utils.ts

359 lines7.9 KB

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
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
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
67​
68export function isValidTimeout(value: any): value is number {
69 return typeof value === 'number' && value >= 0 && value !== Infinity
71​
72export function ensureArray<T>(value: T | T[]): T[] {
73 return Array.isArray(value) ? value : [value]
75​
76export function difference<T>(array1: T[], array2: T[]): T[] {
77 return array1.filter(x => array2.indexOf(x) === -1)
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
85​
86export function timeUntilStale(updatedAt: number, staleTime?: number): number {
87 return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)
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
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
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]
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
191​
192export function getQueryKeyHashFn(
193 options?: QueryOptions<any, any>
194): QueryKeyHashFunction {
195 return options?.queryKeyHashFn || hashQueryKey
197​
198/**
199 * Default query keys hash function.
200 */
201export function hashQueryKey(queryKey: QueryKey): string {
202 return stableValueHash(queryKey)
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 )
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))
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
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
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
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
328​
329function hasObjectPrototype(o: any): boolean {
330 return Object.prototype.toString.call(o) === '[object Object]'
332​
333export function isQueryKey(value: any): value is QueryKey {
334 return typeof value === 'string' || Array.isArray(value)
336​
337export function isError(value: any): value is Error {
338 return value instanceof Error
340​
341export function sleep(timeout: number): Promise<void> {
342 return new Promise(resolve => {
343 setTimeout(resolve, timeout)
344 })
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 )