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

utils.ts

415 lines9.3 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'
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.indexOf(x) === -1)
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 (isQueryKey(arg1)
153 ? [{ ...arg2, queryKey: arg1 }, arg3]
154 : [arg1 || {}, arg2]) 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 (isQueryKey(arg1)
166 ? [{ ...arg2, mutationKey: arg1 }, arg3]
167 : [arg1 || {}, arg2]) as [TFilters, TOptions]
169​
170export function matchQuery(
171 filters: QueryFilters,
172 query: Query<any, any, any, any>
173): boolean {
174 const {
175 type = 'all',
176 exact,
177 fetchStatus,
178 predicate,
179 queryKey,
180 stale,
181 } = filters
182​
183 if (isQueryKey(queryKey)) {
184 if (exact) {
185 if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
186 return false
187 }
188 } else if (!partialMatchKey(query.queryKey, queryKey)) {
189 return false
190 }
191 }
192​
193 if (type !== 'all') {
194 const isActive = query.isActive()
195 if (type === 'active' && !isActive) {
196 return false
197 }
198 if (type === 'inactive' && isActive) {
199 return false
200 }
201 }
202​
203 if (typeof stale === 'boolean' && query.isStale() !== stale) {
204 return false
205 }
206​
207 if (
208 typeof fetchStatus !== 'undefined' &&
209 fetchStatus !== query.state.fetchStatus
210 ) {
211 return false
212 }
213​
214 if (predicate && !predicate(query)) {
215 return false
216 }
217​
218 return true
220​
221export function matchMutation(
222 filters: MutationFilters,
223 mutation: Mutation<any, any>
224): boolean {
225 const { exact, fetching, predicate, mutationKey } = filters
226 if (isQueryKey(mutationKey)) {
227 if (!mutation.options.mutationKey) {
228 return false
229 }
230 if (exact) {
231 if (
232 hashQueryKey(mutation.options.mutationKey) !== hashQueryKey(mutationKey)
233 ) {
234 return false
235 }
236 } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
237 return false
238 }
239 }
240​
241 if (
242 typeof fetching === 'boolean' &&
243 (mutation.state.status === 'loading') !== fetching
244 ) {
245 return false
246 }
247​
248 if (predicate && !predicate(mutation)) {
249 return false
250 }
251​
252 return true
254​
255export function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(
256 queryKey: TQueryKey,
257 options?: QueryOptions<any, any, any, TQueryKey>
258): string {
259 const hashFn = options?.queryKeyHashFn || hashQueryKey
260 return hashFn(queryKey)
262​
263/**
264 * Default query keys hash function.
265 * Hashes the value into a stable hash.
266 */
267export function hashQueryKey(queryKey: QueryKey): string {
268 return JSON.stringify(queryKey, (_, val) =>
269 isPlainObject(val)
270 ? Object.keys(val)
271 .sort()
272 .reduce((result, key) => {
273 result[key] = val[key]
274 return result
275 }, {} as any)
276 : val
277 )
279​
280/**
281 * Checks if key `b` partially matches with key `a`.
282 */
283export function partialMatchKey(a: QueryKey, b: QueryKey): boolean {
284 return partialDeepEqual(a, b)
286​
287/**
288 * Checks if `b` partially matches with `a`.
289 */
290export function partialDeepEqual(a: any, b: any): boolean {
291 if (a === b) {
292 return true
293 }
294​
295 if (typeof a !== typeof b) {
296 return false
297 }
298​
299 if (a && b && typeof a === 'object' && typeof b === 'object') {
300 return !Object.keys(b).some(key => !partialDeepEqual(a[key], b[key]))
301 }
302​
303 return false
305​
306/**
307 * This function returns `a` if `b` is deeply equal.
308 * If not, it will replace any deeply equal children of `b` with those of `a`.
309 * This can be used for structural sharing between JSON values for example.
310 */
311export function replaceEqualDeep<T>(a: unknown, b: T): T
312export function replaceEqualDeep(a: any, b: any): any {
313 if (a === b) {
314 return a
315 }
316​
317 const array = Array.isArray(a) && Array.isArray(b)
318​
319 if (array || (isPlainObject(a) && isPlainObject(b))) {
320 const aSize = array ? a.length : Object.keys(a).length
321 const bItems = array ? b : Object.keys(b)
322 const bSize = bItems.length
323 const copy: any = array ? [] : {}
324​
325 let equalItems = 0
326​
327 for (let i = 0; i < bSize; i++) {
328 const key = array ? i : bItems[i]
329 copy[key] = replaceEqualDeep(a[key], b[key])
330 if (copy[key] === a[key]) {
331 equalItems++
332 }
333 }
334​
335 return aSize === bSize && equalItems === aSize ? a : copy
336 }
337​
338 return b
340​
341/**
342 * Shallow compare objects. Only works with objects that always have the same properties.
343 */
344export function shallowEqualObjects<T>(a: T, b: T): boolean {
345 if ((a && !b) || (b && !a)) {
346 return false
347 }
348​
349 for (const key in a) {
350 if (a[key] !== b[key]) {
351 return false
352 }
353 }
354​
355 return true
357​
358// Copied from: https://github.com/jonschlinkert/is-plain-object
359export function isPlainObject(o: any): o is Object {
360 if (!hasObjectPrototype(o)) {
361 return false
362 }
363​
364 // If has modified constructor
365 const ctor = o.constructor
366 if (typeof ctor === 'undefined') {
367 return true
368 }
369​
370 // If has modified prototype
371 const prot = ctor.prototype
372 if (!hasObjectPrototype(prot)) {
373 return false
374 }
375​
376 // If constructor does not have an Object-specific method
377 if (!prot.hasOwnProperty('isPrototypeOf')) {
378 return false
379 }
380​
381 // Most likely a plain Object
382 return true
384​
385function hasObjectPrototype(o: any): boolean {
386 return Object.prototype.toString.call(o) === '[object Object]'
388​
389export function isQueryKey(value: unknown): value is QueryKey {
390 return Array.isArray(value)
392​
393export function isError(value: any): value is Error {
394 return value instanceof Error
396​
397export function sleep(timeout: number): Promise<void> {
398 return new Promise(resolve => {
399 setTimeout(resolve, timeout)
400 })
402​
403/**
404 * Schedules a microtask.
405 * This can be useful to schedule state updates after rendering.
406 */
407export function scheduleMicrotask(callback: () => void) {
408 sleep(0).then(callback)
410​
411export function getAbortController(): AbortController | undefined {
412 if (typeof AbortController === 'function') {
413 return new AbortController()
414 }