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

utils.ts

448 lines11.1 KB

1import type {
2 DefaultError,
3 Enabled,
4 FetchStatus,
5 MutationKey,
6 MutationStatus,
7 QueryFunction,
8 QueryKey,
9 QueryOptions,
10 StaleTime,
11 StaleTimeFunction,
12} from './types'
13import type { Mutation } from './mutation'
14import type { FetchOptions, Query } from './query'
15​
16// TYPES
17​
18export interface QueryFilters<TQueryKey extends QueryKey = QueryKey> {
19 /**
20 * Filter to active queries, inactive queries or all queries
21 */
22 type?: QueryTypeFilter
23 /**
24 * Match query key exactly
25 */
26 exact?: 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?: TQueryKey
35 /**
36 * Include or exclude stale queries
37 */
38 stale?: boolean
39 /**
40 * Include queries matching their fetchStatus
41 */
42 fetchStatus?: FetchStatus
44​
45export interface MutationFilters<
46 TData = unknown,
47 TError = DefaultError,
48 TVariables = unknown,
49 TContext = unknown,
50> {
51 /**
52 * Match mutation key exactly
53 */
54 exact?: boolean
55 /**
56 * Include mutations matching this predicate function
57 */
58 predicate?: (
59 mutation: Mutation<TData, TError, TVariables, TContext>,
60 ) => boolean
61 /**
62 * Include mutations matching this mutation key
63 */
64 mutationKey?: MutationKey
65 /**
66 * Filter by mutation status
67 */
68 status?: MutationStatus
70​
71export type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)
72​
73export type QueryTypeFilter = 'all' | 'active' | 'inactive'
74​
75// UTILS
76​
77export const isServer = typeof window === 'undefined' || 'Deno' in globalThis
78​
79export function noop(): void
80export function noop(): undefined
81export function noop() {}
82​
83export function functionalUpdate<TInput, TOutput>(
84 updater: Updater<TInput, TOutput>,
85 input: TInput,
86): TOutput {
87 return typeof updater === 'function'
88 ? (updater as (_: TInput) => TOutput)(input)
89 : updater
91​
92export function isValidTimeout(value: unknown): value is number {
93 return typeof value === 'number' && value >= 0 && value !== Infinity
95​
96export function timeUntilStale(updatedAt: number, staleTime?: number): number {
97 return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)
99​
100export function resolveStaleTime<
101 TQueryFnData = unknown,
102 TError = DefaultError,
103 TData = TQueryFnData,
104 TQueryKey extends QueryKey = QueryKey,
105>(
106 staleTime:
107 | undefined
108 | StaleTimeFunction<TQueryFnData, TError, TData, TQueryKey>,
109 query: Query<TQueryFnData, TError, TData, TQueryKey>,
110): StaleTime | undefined {
111 return typeof staleTime === 'function' ? staleTime(query) : staleTime
113​
114export function resolveEnabled<
115 TQueryFnData = unknown,
116 TError = DefaultError,
117 TData = TQueryFnData,
118 TQueryKey extends QueryKey = QueryKey,
119>(
120 enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,
121 query: Query<TQueryFnData, TError, TData, TQueryKey>,
122): boolean | undefined {
123 return typeof enabled === 'function' ? enabled(query) : enabled
125​
126export function matchQuery(
127 filters: QueryFilters,
128 query: Query<any, any, any, any>,
129): boolean {
130 const {
131 type = 'all',
132 exact,
133 fetchStatus,
134 predicate,
135 queryKey,
136 stale,
137 } = filters
138​
139 if (queryKey) {
140 if (exact) {
141 if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
142 return false
143 }
144 } else if (!partialMatchKey(query.queryKey, queryKey)) {
145 return false
146 }
147 }
148​
149 if (type !== 'all') {
150 const isActive = query.isActive()
151 if (type === 'active' && !isActive) {
152 return false
153 }
154 if (type === 'inactive' && isActive) {
155 return false
156 }
157 }
158​
159 if (typeof stale === 'boolean' && query.isStale() !== stale) {
160 return false
161 }
162​
163 if (fetchStatus && fetchStatus !== query.state.fetchStatus) {
164 return false
165 }
166​
167 if (predicate && !predicate(query)) {
168 return false
169 }
170​
171 return true
173​
174export function matchMutation(
175 filters: MutationFilters,
176 mutation: Mutation<any, any>,
177): boolean {
178 const { exact, status, predicate, mutationKey } = filters
179 if (mutationKey) {
180 if (!mutation.options.mutationKey) {
181 return false
182 }
183 if (exact) {
184 if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
185 return false
186 }
187 } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
188 return false
189 }
190 }
191​
192 if (status && mutation.state.status !== status) {
193 return false
194 }
195​
196 if (predicate && !predicate(mutation)) {
197 return false
198 }
199​
200 return true
202​
203export function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(
204 queryKey: TQueryKey,
205 options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,
206): string {
207 const hashFn = options?.queryKeyHashFn || hashKey
208 return hashFn(queryKey)
210​
211/**
212 * Default query & mutation keys hash function.
213 * Hashes the value into a stable hash.
214 */
215export function hashKey(queryKey: QueryKey | MutationKey): string {
216 return JSON.stringify(queryKey, (_, val) =>
217 isPlainObject(val)
218 ? Object.keys(val)
219 .sort()
220 .reduce((result, key) => {
221 result[key] = val[key]
222 return result
223 }, {} as any)
224 : val,
225 )
227​
228/**
229 * Checks if key `b` partially matches with key `a`.
230 */
231export function partialMatchKey(a: QueryKey, b: QueryKey): boolean
232export function partialMatchKey(a: any, b: any): boolean {
233 if (a === b) {
234 return true
235 }
236​
237 if (typeof a !== typeof b) {
238 return false
239 }
240​
241 if (a && b && typeof a === 'object' && typeof b === 'object') {
242 return Object.keys(b).every((key) => partialMatchKey(a[key], b[key]))
243 }
244​
245 return false
247​
248/**
249 * This function returns `a` if `b` is deeply equal.
250 * If not, it will replace any deeply equal children of `b` with those of `a`.
251 * This can be used for structural sharing between JSON values for example.
252 */
253export function replaceEqualDeep<T>(a: unknown, b: T): T
254export function replaceEqualDeep(a: any, b: any): any {
255 if (a === b) {
256 return a
257 }
258​
259 const array = isPlainArray(a) && isPlainArray(b)
260​
261 if (array || (isPlainObject(a) && isPlainObject(b))) {
262 const aItems = array ? a : Object.keys(a)
263 const aSize = aItems.length
264 const bItems = array ? b : Object.keys(b)
265 const bSize = bItems.length
266 const copy: any = array ? [] : {}
267 const aItemsSet = new Set(aItems)
268​
269 let equalItems = 0
270​
271 for (let i = 0; i < bSize; i++) {
272 const key = array ? i : bItems[i]
273 if (
274 ((!array && aItemsSet.has(key)) || array) &&
275 a[key] === undefined &&
276 b[key] === undefined
277 ) {
278 copy[key] = undefined
279 equalItems++
280 } else {
281 copy[key] = replaceEqualDeep(a[key], b[key])
282 if (copy[key] === a[key] && a[key] !== undefined) {
283 equalItems++
284 }
285 }
286 }
287​
288 return aSize === bSize && equalItems === aSize ? a : copy
289 }
290​
291 return b
293​
294/**
295 * Shallow compare objects.
296 */
297export function shallowEqualObjects<T extends Record<string, any>>(
298 a: T,
299 b: T | undefined,
300): boolean {
301 if (!b || Object.keys(a).length !== Object.keys(b).length) {
302 return false
303 }
304​
305 for (const key in a) {
306 if (a[key] !== b[key]) {
307 return false
308 }
309 }
310​
311 return true
313​
314export function isPlainArray(value: unknown) {
315 return Array.isArray(value) && value.length === Object.keys(value).length
317​
318// Copied from: https://github.com/jonschlinkert/is-plain-object
319// eslint-disable-next-line @typescript-eslint/no-wrapper-object-types
320export function isPlainObject(o: any): o is Object {
321 if (!hasObjectPrototype(o)) {
322 return false
323 }
324​
325 // If has no constructor
326 const ctor = o.constructor
327 if (ctor === undefined) {
328 return true
329 }
330​
331 // If has modified prototype
332 const prot = ctor.prototype
333 if (!hasObjectPrototype(prot)) {
334 return false
335 }
336​
337 // If constructor does not have an Object-specific method
338 if (!prot.hasOwnProperty('isPrototypeOf')) {
339 return false
340 }
341​
342 // Handles Objects created by Object.create(<arbitrary prototype>)
343 if (Object.getPrototypeOf(o) !== Object.prototype) {
344 return false
345 }
346​
347 // Most likely a plain Object
348 return true
350​
351function hasObjectPrototype(o: any): boolean {
352 return Object.prototype.toString.call(o) === '[object Object]'
354​
355export function sleep(timeout: number): Promise<void> {
356 return new Promise((resolve) => {
357 setTimeout(resolve, timeout)
358 })
360​
361export function replaceData<
362 TData,
363 TOptions extends QueryOptions<any, any, any, any>,
364>(prevData: TData | undefined, data: TData, options: TOptions): TData {
365 if (typeof options.structuralSharing === 'function') {
366 return options.structuralSharing(prevData, data) as TData
367 } else if (options.structuralSharing !== false) {
368 if (process.env.NODE_ENV !== 'production') {
369 try {
370 return replaceEqualDeep(prevData, data)
371 } catch (error) {
372 console.error(
373 `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,
374 )
375​
376 // Prevent the replaceEqualDeep from being called again down below.
377 throw error
378 }
379 }
380 // Structurally share data between prev and new data if needed
381 return replaceEqualDeep(prevData, data)
382 }
383 return data
385​
386export function keepPreviousData<T>(
387 previousData: T | undefined,
388): T | undefined {
389 return previousData
391​
392export function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {
393 const newItems = [...items, item]
394 return max && newItems.length > max ? newItems.slice(1) : newItems
396​
397export function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {
398 const newItems = [item, ...items]
399 return max && newItems.length > max ? newItems.slice(0, -1) : newItems
401​
402export const skipToken = Symbol()
403export type SkipToken = typeof skipToken
404​
405export function ensureQueryFn<
406 TQueryFnData = unknown,
407 TQueryKey extends QueryKey = QueryKey,
408>(
409 options: {
410 queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken
411 queryHash?: string
412 },
413 fetchOptions?: FetchOptions<TQueryFnData>,
414): QueryFunction<TQueryFnData, TQueryKey> {
415 if (process.env.NODE_ENV !== 'production') {
416 if (options.queryFn === skipToken) {
417 console.error(
418 `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,
419 )
420 }
421 }
422​
423 // if we attempt to retry a fetch that was triggered from an initialPromise
424 // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise
425 // if an observer has already mounted, we will be able to retry with that queryFn
426 if (!options.queryFn && fetchOptions?.initialPromise) {
427 return () => fetchOptions.initialPromise!
428 }
429​
430 if (!options.queryFn || options.queryFn === skipToken) {
431 return () =>
432 Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))
433 }
434​
435 return options.queryFn
437​
438export function shouldThrowError<T extends (...args: Array<any>) => boolean>(
439 throwOnError: boolean | T | undefined,
440 params: Parameters<T>,
441): boolean {
442 // Allow throwOnError function to override throwing behavior on a per-error basis
443 if (typeof throwOnError === 'function') {
444 return throwOnError(...params)
445 }
446​
447 return !!throwOnError