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

utils.ts

444 lines11.0 KB

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