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

utils.ts

440 lines10.1 KB

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
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
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
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
85​
86export function isValidTimeout(value: unknown): value is number {
87 return typeof value === 'number' && value >= 0 && value !== Infinity
89​
90export function difference<T>(array1: T[], array2: T[]): T[] {
91 return array1.filter((x) => !array2.includes(x))
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
99​
100export function timeUntilStale(updatedAt: number, staleTime?: number): number {
101 return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)
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
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
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]
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]
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
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
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)
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 )
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)
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
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
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
361​
362export function isPlainArray(value: unknown) {
363 return Array.isArray(value) && value.length === Object.keys(value).length
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
392​
393function hasObjectPrototype(o: any): boolean {
394 return Object.prototype.toString.call(o) === '[object Object]'
396​
397export function isQueryKey(value: unknown): value is QueryKey {
398 return Array.isArray(value)
400​
401export function isError(value: any): value is Error {
402 return value instanceof Error
404​
405export function sleep(timeout: number): Promise<void> {
406 return new Promise((resolve) => {
407 setTimeout(resolve, timeout)
408 })
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)
418​
419export function getAbortController(): AbortController | undefined {
420 if (typeof AbortController === 'function') {
421 return new AbortController()
422 }
423 return
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