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

utils.ts

409 lines10.0 KB

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