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

utils.ts

455 lines10.4 KB

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