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

utils.ts

410 lines9.9 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 {
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?: QueryKey
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 /**
46 * Match mutation key exactly
47 */
48 exact?: boolean
49 /**
50 * Include mutations matching this predicate function
51 */
52 predicate?: (mutation: Mutation<any, any, any>) => boolean
53 /**
54 * Include mutations matching this mutation key
55 */
56 mutationKey?: MutationKey
57 /**
58 * Filter by mutation status
59 */
60 status?: MutationStatus
62​
63export type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)
64​
65export type QueryTypeFilter = 'all' | 'active' | 'inactive'
66​
67// UTILS
68​
69export const isServer = typeof window === 'undefined' || 'Deno' in globalThis
70​
71export function noop(): undefined {}
72​
73export function functionalUpdate<TInput, TOutput>(
74 updater: Updater<TInput, TOutput>,
75 input: TInput,
76): TOutput {
77 return typeof updater === 'function'
78 ? (updater as (_: TInput) => TOutput)(input)
79 : updater
81​
82export function isValidTimeout(value: unknown): value is number {
83 return typeof value === 'number' && value >= 0 && value !== Infinity
85​
86export function timeUntilStale(updatedAt: number, staleTime?: number): number {
87 return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)
89​
90export function resolveStaleTime<
91 TQueryFnData = unknown,
92 TError = DefaultError,
93 TData = TQueryFnData,
94 TQueryKey extends QueryKey = QueryKey,
95>(
96 staleTime: undefined | StaleTime<TQueryFnData, TError, TData, TQueryKey>,
97 query: Query<TQueryFnData, TError, TData, TQueryKey>,
98): number | undefined {
99 return typeof staleTime === 'function' ? staleTime(query) : staleTime
101​
102export function resolveEnabled<
103 TQueryFnData = unknown,
104 TError = DefaultError,
105 TData = TQueryFnData,
106 TQueryKey extends QueryKey = QueryKey,
107>(
108 enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,
109 query: Query<TQueryFnData, TError, TData, TQueryKey>,
110): boolean | undefined {
111 return typeof enabled === 'function' ? enabled(query) : enabled
113​
114export function matchQuery(
115 filters: QueryFilters,
116 query: Query<any, any, any, any>,
117): boolean {
118 const {
119 type = 'all',
120 exact,
121 fetchStatus,
122 predicate,
123 queryKey,
124 stale,
125 } = filters
126​
127 if (queryKey) {
128 if (exact) {
129 if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
130 return false
131 }
132 } else if (!partialMatchKey(query.queryKey, queryKey)) {
133 return false
134 }
135 }
136​
137 if (type !== 'all') {
138 const isActive = query.isActive()
139 if (type === 'active' && !isActive) {
140 return false
141 }
142 if (type === 'inactive' && isActive) {
143 return false
144 }
145 }
146​
147 if (typeof stale === 'boolean' && query.isStale() !== stale) {
148 return false
149 }
150​
151 if (fetchStatus && fetchStatus !== query.state.fetchStatus) {
152 return false
153 }
154​
155 if (predicate && !predicate(query)) {
156 return false
157 }
158​
159 return true
161​
162export function matchMutation(
163 filters: MutationFilters,
164 mutation: Mutation<any, any>,
165): boolean {
166 const { exact, status, predicate, mutationKey } = filters
167 if (mutationKey) {
168 if (!mutation.options.mutationKey) {
169 return false
170 }
171 if (exact) {
172 if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
173 return false
174 }
175 } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
176 return false
177 }
178 }
179​
180 if (status && mutation.state.status !== status) {
181 return false
182 }
183​
184 if (predicate && !predicate(mutation)) {
185 return false
186 }
187​
188 return true
190​
191export function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(
192 queryKey: TQueryKey,
193 options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,
194): string {
195 const hashFn = options?.queryKeyHashFn || hashKey
196 return hashFn(queryKey)
198​
199/**
200 * Default query & mutation keys hash function.
201 * Hashes the value into a stable hash.
202 */
203export function hashKey(queryKey: QueryKey | MutationKey): string {
204 return JSON.stringify(queryKey, (_, val) =>
205 isPlainObject(val)
206 ? Object.keys(val)
207 .sort()
208 .reduce((result, key) => {
209 result[key] = val[key]
210 return result
211 }, {} as any)
212 : val,
213 )
215​
216/**
217 * Checks if key `b` partially matches with key `a`.
218 */
219export function partialMatchKey(a: QueryKey, b: QueryKey): boolean
220export function partialMatchKey(a: any, b: any): boolean {
221 if (a === b) {
222 return true
223 }
224​
225 if (typeof a !== typeof b) {
226 return false
227 }
228​
229 if (a && b && typeof a === 'object' && typeof b === 'object') {
230 return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]))
231 }
232​
233 return false
235​
236/**
237 * This function returns `a` if `b` is deeply equal.
238 * If not, it will replace any deeply equal children of `b` with those of `a`.
239 * This can be used for structural sharing between JSON values for example.
240 */
241export function replaceEqualDeep<T>(a: unknown, b: T): T
242export function replaceEqualDeep(a: any, b: any): any {
243 if (a === b) {
244 return a
245 }
246​
247 const array = isPlainArray(a) && isPlainArray(b)
248​
249 if (array || (isPlainObject(a) && isPlainObject(b))) {
250 const aItems = array ? a : Object.keys(a)
251 const aSize = aItems.length
252 const bItems = array ? b : Object.keys(b)
253 const bSize = bItems.length
254 const copy: any = array ? [] : {}
255​
256 let equalItems = 0
257​
258 for (let i = 0; i < bSize; i++) {
259 const key = array ? i : bItems[i]
260 if (
261 ((!array && aItems.includes(key)) || array) &&
262 a[key] === undefined &&
263 b[key] === undefined
264 ) {
265 copy[key] = undefined
266 equalItems++
267 } else {
268 copy[key] = replaceEqualDeep(a[key], b[key])
269 if (copy[key] === a[key] && a[key] !== undefined) {
270 equalItems++
271 }
272 }
273 }
274​
275 return aSize === bSize && equalItems === aSize ? a : copy
276 }
277​
278 return b
280​
281/**
282 * Shallow compare objects.
283 */
284export function shallowEqualObjects<T extends Record<string, any>>(
285 a: T,
286 b: T | undefined,
287): boolean {
288 if (!b || Object.keys(a).length !== Object.keys(b).length) {
289 return false
290 }
291​
292 for (const key in a) {
293 if (a[key] !== b[key]) {
294 return false
295 }
296 }
297​
298 return true
300​
301export function isPlainArray(value: unknown) {
302 return Array.isArray(value) && value.length === Object.keys(value).length
304​
305// Copied from: https://github.com/jonschlinkert/is-plain-object
306export function isPlainObject(o: any): o is Object {
307 if (!hasObjectPrototype(o)) {
308 return false
309 }
310​
311 // If has no constructor
312 const ctor = o.constructor
313 if (ctor === undefined) {
314 return true
315 }
316​
317 // If has modified prototype
318 const prot = ctor.prototype
319 if (!hasObjectPrototype(prot)) {
320 return false
321 }
322​
323 // If constructor does not have an Object-specific method
324 if (!prot.hasOwnProperty('isPrototypeOf')) {
325 return false
326 }
327​
328 // Handles Objects created by Object.create(<arbitrary prototype>)
329 if (Object.getPrototypeOf(o) !== Object.prototype) {
330 return false
331 }
332​
333 // Most likely a plain Object
334 return true
336​
337function hasObjectPrototype(o: any): boolean {
338 return Object.prototype.toString.call(o) === '[object Object]'
340​
341export function sleep(timeout: number): Promise<void> {
342 return new Promise((resolve) => {
343 setTimeout(resolve, timeout)
344 })
346​
347export function replaceData<
348 TData,
349 TOptions extends QueryOptions<any, any, any, any>,
350>(prevData: TData | undefined, data: TData, options: TOptions): TData {
351 if (typeof options.structuralSharing === 'function') {
352 return options.structuralSharing(prevData, data) as TData
353 } else if (options.structuralSharing !== false) {
354 // Structurally share data between prev and new data if needed
355 return replaceEqualDeep(prevData, data)
356 }
357 return data
359​
360export function keepPreviousData<T>(
361 previousData: T | undefined,
362): T | undefined {
363 return previousData
365​
366export function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {
367 const newItems = [...items, item]
368 return max && newItems.length > max ? newItems.slice(1) : newItems
370​
371export function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {
372 const newItems = [item, ...items]
373 return max && newItems.length > max ? newItems.slice(0, -1) : newItems
375​
376export const skipToken = Symbol()
377export type SkipToken = typeof skipToken
378​
379export function ensureQueryFn<
380 TQueryFnData = unknown,
381 TQueryKey extends QueryKey = QueryKey,
382>(
383 options: {
384 queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken
385 queryHash?: string
386 },
387 fetchOptions?: FetchOptions<TQueryFnData>,
388): QueryFunction<TQueryFnData, TQueryKey> {
389 if (process.env.NODE_ENV !== 'production') {
390 if (options.queryFn === skipToken) {
391 console.error(
392 `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,
393 )
394 }
395 }
396​
397 // if we attempt to retry a fetch that was triggered from an initialPromise
398 // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise
399 // if an observer has already mounted, we will be able to retry with that queryFn
400 if (!options.queryFn && fetchOptions?.initialPromise) {
401 return () => fetchOptions.initialPromise!
402 }
403​
404 if (!options.queryFn || options.queryFn === skipToken) {
405 return () =>
406 Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))
407 }
408​
409 return options.queryFn