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

utils.ts

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