Open History to see the last commit
1import { timeoutManager } from './timeoutManager'
2import type {
3 CacheKeyConfig,
4 DefaultError,
5 EqualityFn,
6 FetchStatus,
7 MutationKey,
8 MutationStatus,
9 QueryFunction,
10 QueryKey,
11 QueryOptions,
12} from './types'
13import type { Mutation } from './mutation'
14import type { FetchOptions, Query } from './query'
15β
16// TYPES
17β
18type DropLast<T extends ReadonlyArray<unknown>> = T extends readonly [
19 ...infer R,
20 unknown,
21]
22 ? readonly [...R]
23 : never
24β
25type TuplePrefixes<T extends ReadonlyArray<unknown>> = T extends readonly []
26 ? readonly []
27 : TuplePrefixes<DropLast<T>> | T
28β
29/**
30 * Filters used to select queries, for example in `queryClient.getQueriesData` or `queryClient.invalidateQueries`.
31 * All provided filters must match; filters that are left unspecified are ignored.
32 */
33export interface QueryFilters<TQueryKey extends QueryKey = QueryKey> {
34 /**
35 * Filter to active queries, inactive queries or all queries
36 * @defaultValue 'all'
37 */
38 type?: QueryTypeFilter
39 /**
40 * Match query key exactly
41 */
42 exact?: boolean
43 /**
44 * Include queries matching this predicate function
45 */
46 predicate?: (query: Query) => boolean
47 /**
48 * Include queries matching this query key
49 */
50 queryKey?: TQueryKey | TuplePrefixes<TQueryKey>
51 /**
52 * Include or exclude stale queries
53 */
54 stale?: boolean
55 /**
56 * Include queries matching their fetchStatus
57 */
58 fetchStatus?: FetchStatus
59}
60β
61/**
62 * Filters used to select mutations, for example in `mutationCache.findAll` or `queryClient.isMutating`.
63 * All provided filters must match; filters that are left unspecified are ignored.
64 */
65export interface MutationFilters<
66 TData = unknown,
67 TError = DefaultError,
68 TVariables = unknown,
69 TOnMutateResult = unknown,
70> {
71 /**
72 * Match mutation key exactly
73 */
74 exact?: boolean
75 /**
76 * Include mutations matching this predicate function
77 */
78 predicate?: (
79 mutation: Mutation<TData, TError, TVariables, TOnMutateResult>,
80 ) => boolean
81 /**
82 * Include mutations matching this mutation key
83 */
84 mutationKey?: TuplePrefixes<MutationKey>
85 /**
86 * Filter by mutation status
87 */
88 status?: MutationStatus
89}
90β
91/**
92 * Either a plain value of type `TOutput`, or a function that receives `TInput` and returns `TOutput`.
93 * Used for example by `setQueryData`-style updaters, which accept either the new data directly or a
94 * function that computes it from the previous data. See {@link functionalUpdate}.
95 * @example
96 * ```ts
97 * queryClient.setQueryData(['posts'], newPosts)
98 *
99 * // Or, using an updater function that receives the current data:
100 * queryClient.setQueryData(['posts'], (oldPosts) =>
101 * oldPosts ? [...oldPosts, newPost] : oldPosts,
102 * )
103 * ```
104 */
105export type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)
106β
107/**
108 * Which queries a filter matches: all of them, only active ones (with enabled observers), or only
109 * inactive ones.
110 */
111export type QueryTypeFilter = 'all' | 'active' | 'inactive'
112β
113// UTILS
114β
115/**
116 * @deprecated use `environmentManager.isServer()` instead.
117 */
118export const isServer = typeof window === 'undefined' || 'Deno' in globalThis
119β
120/**
121 * A function that does nothing.
122 */
123export function noop(): void
124export function noop(): undefined
125export function noop() {}
126β
127/**
128 * Resolves an {@link Updater}: calls it with `input` if it is a function, otherwise returns it as
129 * is.
130 * @param updater - The new value, or a function that receives `input` and returns the new value.
131 * @param input - The current value, passed to `updater` if it is a function.
132 * @returns The new value.
133 */
134export function functionalUpdate<TInput, TOutput>(
135 updater: Updater<TInput, TOutput>,
136 input: TInput,
137): TOutput {
138 return typeof updater === 'function'
139 ? (updater as (_: TInput) => TOutput)(input)
140 : updater
141}
142β
143/**
144 * Checks whether a value can be used as a timeout: a non-negative, finite number.
145 * @param value - The value to check.
146 * @returns `true` if `value` is a number that is `>= 0` and not `Infinity`.
147 */
148export function isValidTimeout(value: unknown): value is number {
149 return typeof value === 'number' && value >= 0 && value !== Infinity
150}
151β
152/**
153 * Calculates how long until data updated at `updatedAt` becomes stale.
154 * @param updatedAt - The timestamp, in milliseconds, at which the data was last updated.
155 * @param staleTime - The time, in milliseconds, after which data is considered stale. Defaults to
156 * `0`.
157 * @returns The remaining time in milliseconds, or `0` if the data is already stale.
158 */
159export function timeUntilStale(updatedAt: number, staleTime?: number): number {
160 return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)
161}
162β
163/**
164 * Resolves an option that can be given either as a value or as a function of the query, such as
165 * `staleTime`.
166 * @param value - The option value, or a function that receives `query` and returns the value.
167 * @param query - The query passed to `value` if it is a function.
168 * @returns The resolved value, or `undefined` if `value` is `undefined`.
169 */
170export function resolveQueryValue<
171 TValue,
172 TQueryFnData = unknown,
173 TError = DefaultError,
174 TData = TQueryFnData,
175 TQueryKey extends QueryKey = QueryKey,
176>(
177 value:
178 | undefined
179 | TValue
180 | ((query: Query<TQueryFnData, TError, TData, TQueryKey>) => TValue),
181 query: Query<TQueryFnData, TError, TData, TQueryKey>,
182): TValue | undefined {
183 return typeof value === 'function'
184 ? (
185 value as (
186 query: Query<TQueryFnData, TError, TData, TQueryKey>,
187 ) => TValue
188 )(query)
189 : value
190}
191β
192/**
193 * Checks whether a query matches the given {@link QueryFilters}.
194 * Every filter that is specified must match; filters that are left unspecified are ignored.
195 * @param filters - The filters to check the query against.
196 * @param query - The query to check.
197 * @param keyConfig - The cache configuration for key comparison and hashing.
198 * @returns `true` if the query matches every specified filter.
199 * @example
200 * ```ts
201 * const queryCache = queryClient.getQueryCache()
202 *
203 * const matchingQueries = queryCache
204 * .getAll()
205 * .filter((query) => matchQuery({ queryKey: ['posts'] }, query))
206 * ```
207 */
208export function matchQuery(
209 filters: QueryFilters,
210 query: Query<any, any, any, any>,
211 keyConfig?: CacheKeyConfig<QueryKey>,
212): boolean {
213 const {
214 type = 'all',
215 exact,
216 fetchStatus,
217 predicate,
218 queryKey,
219 stale,
220 } = filters
221β
222 if (queryKey) {
223 if (exact) {
224 if (
225 query.queryHash !== hashKeyByOptions(queryKey, keyConfig, query.options)
226 ) {
227 return false
228 }
229 } else if (
230 !partialMatchKey(query.queryKey, queryKey, keyConfig?.equalityFn)
231 ) {
232 return false
233 }
234 }
235β
236 if (type !== 'all') {
237 const isActive = query.isActive()
238 if (type === 'active' && !isActive) {
239 return false
240 }
241 if (type === 'inactive' && isActive) {
242 return false
243 }
244 }
245β
246 if (typeof stale === 'boolean' && query.isStale() !== stale) {
247 return false
248 }
249β
250 if (fetchStatus && fetchStatus !== query.state.fetchStatus) {
251 return false
252 }
253β
254 if (predicate && !predicate(query)) {
255 return false
256 }
257β
258 return true
259}
260β
261/**
262 * Checks whether a mutation matches the given {@link MutationFilters}.
263 * Every filter that is specified must match; filters that are left unspecified are ignored.
264 * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match.
265 * @param filters - The filters to check the mutation against.
266 * @param mutation - The mutation to check.
267 * @param keyConfig - The cache configuration for key comparison and hashing.
268 * @returns `true` if the mutation matches every specified filter.
269 * @example
270 * ```ts
271 * const mutationCache = queryClient.getMutationCache()
272 *
273 * const matchingMutations = mutationCache
274 * .getAll()
275 * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation))
276 * ```
277 */
278export function matchMutation(
279 filters: MutationFilters,
280 mutation: Mutation<any, any>,
281 keyConfig?: CacheKeyConfig<MutationKey>,
282): boolean {
283 const { exact, status, predicate, mutationKey } = filters
284 if (mutationKey) {
285 if (!mutation.options.mutationKey) {
286 return false
287 }
288 if (exact) {
289 if (
290 hashKeyByOptions(mutation.options.mutationKey, keyConfig) !==
291 hashKeyByOptions(mutationKey, keyConfig)
292 ) {
293 return false
294 }
295 } else if (
296 !partialMatchKey(
297 mutation.options.mutationKey,
298 mutationKey,
299 keyConfig?.equalityFn,
300 )
301 ) {
302 return false
303 }
304 }
305β
306 if (status && mutation.state.status !== status) {
307 return false
308 }
309β
310 if (predicate && !predicate(mutation)) {
311 return false
312 }
313β
314 return true
315}
316β
317/**
318 * Hashes a cache key with the cache's `hashFn`, then the query's `queryKeyHashFn`, falling back to {@link hashKey}.
319 * @param cacheKey - The query or mutation key to hash.
320 * @param keyConfig - The cache configuration that may provide a custom `hashFn`.
321 * @param options - The query options that may provide a custom `queryKeyHashFn`.
322 * @returns The hash, a string that identifies the key in the cache.
323 */
324export function hashKeyByOptions<
325 TCacheKey extends ReadonlyArray<unknown> = ReadonlyArray<unknown>,
326>(
327 cacheKey: TCacheKey,
328 keyConfig: CacheKeyConfig<TCacheKey> | undefined,
329 options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,
330): string {
331 const queryKeyHashFn = keyConfig?.hashFn ?? options?.queryKeyHashFn ?? hashKey
332 return queryKeyHashFn(cacheKey)
333}
334β
335/**
336 * Default query & mutation keys hash function.
337 * Hashes the value into a stable hash.
338 * @param queryKey - The query or mutation key to hash.
339 * @returns The stable hash of the key, as a JSON string.
340 * @example
341 * ```ts
342 * // Object keys are sorted, so key order doesn't affect the hash:
343 * hashKey(['todos', { page: 1, filter: 'done' }]) // === '["todos",{"filter":"done","page":1}]'
344 * ```
345 */
346export function hashKey(queryKey: QueryKey | MutationKey): string {
347 return JSON.stringify(queryKey, (_, val) =>
348 isPlainObject(val)
349 ? Object.keys(val)
350 .sort()
351 .reduce((result, key) => {
352 result[key] = val[key]
353 return result
354 }, {} as any)
355 : val,
356 )
357}
358β
359const defaultEqualityFn: EqualityFn = (a, b) => a === b
360β
361/**
362 * Checks if key `b` partially matches with key `a`.
363 * @param a - The key to check, e.g. a query's own key.
364 * @param b - The (partial) key to match against `a`.
365 * @param equalityFn - Compares individual key values. Defaults to strict equality.
366 * @returns `true` if every array element or object property in `b` matches the one at the same
367 * position in `a`.
368 */
369export function partialMatchKey(
370 a: QueryKey,
371 b: QueryKey,
372 equalityFn?: EqualityFn,
373): boolean
374export function partialMatchKey(
375 a: unknown,
376 b: unknown,
377 equalityFn?: EqualityFn,
378): boolean
379export function partialMatchKey(
380 a: any,
381 b: any,
382 equalityFn: EqualityFn = defaultEqualityFn,
383): boolean {
384 if (equalityFn(a, b)) {
385 return true
386 }
387β
388 if (typeof a !== typeof b) {
389 return false
390 }
391β
392 if (isPlainArray(a) && isPlainArray(b)) {
393 if (b.length > a.length) return false
394 for (let i = 0; i < b.length; i++) {
395 if (!partialMatchKey(a[i], b[i], equalityFn)) {
396 return false
397 }
398 }
399 return true
400 }
401β
402 if (isPlainObject(a) && isPlainObject(b)) {
403 const bKeys = Object.keys(b)
404 for (const key of bKeys) {
405 if (!partialMatchKey(a[key], b[key], equalityFn)) {
406 return false
407 }
408 }
409 return true
410 }
411β
412 return false
413}
414β
415const hasOwn = Object.prototype.hasOwnProperty
416β
417/**
418 * This function returns `a` if `b` is deeply equal.
419 * If not, it will replace any deeply equal children of `b` with those of `a`.
420 * This can be used for structural sharing between JSON values for example.
421 * An optional equality function can be used for custom value types.
422 * @param a - The previous value, whose deeply equal parts are reused.
423 * @param b - The new value.
424 * @param equalityFn - Compares values for structural sharing. Defaults to strict equality.
425 * @returns `a` if `b` is deeply equal to it, otherwise `b` with its deeply equal parts replaced by
426 * those of `a`.
427 */
428export function replaceEqualDeep<T>(
429 a: unknown,
430 b: T,
431 equalityFn?: EqualityFn,
432): T
433export function replaceEqualDeep(
434 a: any,
435 b: any,
436 equalityFn: EqualityFn = defaultEqualityFn,
437): any {
438 return replaceEqualDeepInternal(a, b, equalityFn, 0)
439}
440β
441/**
442 * Reuses deeply equal values while limiting recursion to 500 levels.
443 * @param a - The previous value.
444 * @param b - The new value.
445 * @param equalityFn - Compares values for structural sharing.
446 * @param depth - The current recursion depth.
447 * @returns The new value with deeply equal parts of the previous value reused.
448 */
449function replaceEqualDeepInternal(
450 a: any,
451 b: any,
452 equalityFn: EqualityFn,
453 depth: number,
454): any {
455 if (equalityFn(a, b)) {
456 return a
457 }
458β
459 if (depth > 500) return b
460β
461 const array = isPlainArray(a) && isPlainArray(b)
462β
463 if (!array && !(isPlainObject(a) && isPlainObject(b))) return b
464β
465 const aItems = array ? a : Object.keys(a)
466 const aSize = aItems.length
467 const bItems = array ? b : Object.keys(b)
468 const bSize = bItems.length
469 const copy: any = array ? new Array(bSize) : {}
470β
471 let equalItems = 0
472β
473 for (let i = 0; i < bSize; i++) {
474 const key: any = array ? i : bItems[i]
475 const aItem = a[key]
476 const bItem = b[key]
477β
478 if (equalityFn(aItem, bItem)) {
479 copy[key] = aItem
480 if (array ? i < aSize : hasOwn.call(a, key)) equalItems++
481 continue
482 }
483β
484 if (
485 aItem === null ||
486 bItem === null ||
487 typeof aItem !== 'object' ||
488 typeof bItem !== 'object'
489 ) {
490 copy[key] = bItem
491 continue
492 }
493β
494 const v = replaceEqualDeepInternal(aItem, bItem, equalityFn, depth + 1)
495 copy[key] = v
496 if (v === aItem) equalItems++
497 }
498β
499 return aSize === bSize && equalItems === aSize ? a : copy
500}
501β
502/**
503 * Shallow compare objects.
504 * @param a - The first object.
505 * @param b - The second object, or `undefined`.
506 * @returns `true` if both objects have the same keys, with strictly equal values for each key.
507 */
508export function shallowEqualObjects<T extends Record<string, any>>(
509 a: T,
510 b: T | undefined,
511): boolean {
512 if (!b || Object.keys(a).length !== Object.keys(b).length) {
513 return false
514 }
515β
516 for (const key in a) {
517 if (a[key] !== b[key]) {
518 return false
519 }
520 }
521β
522 return true
523}
524β
525/**
526 * Checks whether a value is an array with no holes and no extra properties.
527 * @param value - The value to check.
528 * @returns `true` if `value` is an array whose number of own keys equals its `length`.
529 */
530export function isPlainArray(value: unknown): value is Array<unknown> {
531 return Array.isArray(value) && value.length === Object.keys(value).length
532}
533β
534// Copied from: https://github.com/jonschlinkert/is-plain-object
535/**
536 * Checks whether a value is a plain object, e.g. created with an object literal or
537 * `Object.create(null)`.
538 * @param o - The value to check.
539 * @returns `true` if `o` is a plain object.
540 */
541export function isPlainObject(o: any): o is Record<PropertyKey, unknown> {
542 if (!hasObjectPrototype(o)) {
543 return false
544 }
545β
546 // If has no constructor
547 const objectPrototype = Object.getPrototypeOf(o)
548 const ctor = objectPrototype?.constructor
549 if (ctor === undefined) {
550 return true
551 }
552β
553 if (typeof ctor !== 'function') {
554 return false
555 }
556β
557 // If has modified prototype
558 const prot = ctor.prototype
559 if (!hasObjectPrototype(prot)) {
560 return false
561 }
562β
563 // If constructor does not have an Object-specific method
564 if (!prot.hasOwnProperty('isPrototypeOf')) {
565 return false
566 }
567β
568 // Handles Objects created by Object.create(<arbitrary prototype>)
569 if (objectPrototype !== Object.prototype) {
570 return false
571 }
572β
573 // Most likely a plain Object
574 return true
575}
576β
577/**
578 * Checks whether a value's `Object.prototype.toString` tag is `[object Object]`.
579 * @param o - The value to check.
580 * @returns `true` if the tag is `[object Object]`.
581 */
582function hasObjectPrototype(o: any): boolean {
583 return Object.prototype.toString.call(o) === '[object Object]'
584}
585β
586/**
587 * Waits for the given time, using the configured {@link timeoutManager}.
588 * @param timeout - The time to wait, in milliseconds.
589 * @returns A promise that resolves after `timeout` milliseconds.
590 */
591export function sleep(timeout: number): Promise<void> {
592 return new Promise((resolve) => {
593 timeoutManager.setTimeout(resolve, timeout)
594 })
595}
596β
597/**
598 * Applies a query's `structuralSharing` option when writing new data.
599 * @param prevData - The previously cached data.
600 * @param data - The new data.
601 * @param options - The query options, whose `structuralSharing` decides how the data is merged.
602 * @returns The result of a custom `structuralSharing` function, `data` with its unchanged parts
603 * replaced by those of `prevData` by default, or `data` as is if `structuralSharing` is `false`.
604 * @throws {Error} The error from the default structural sharing, e.g. when the data is not JSON serializable.
605 * Outside production, it is also logged to the console.
606 */
607export function replaceData<
608 TData,
609 TOptions extends QueryOptions<any, any, any, any>,
610>(prevData: TData | undefined, data: TData, options: TOptions): TData {
611 if (typeof options.structuralSharing === 'function') {
612 return options.structuralSharing(prevData, data) as TData
613 } else if (options.structuralSharing !== false) {
614 if (process.env.NODE_ENV !== 'production') {
615 try {
616 return replaceEqualDeep(prevData, data)
617 } catch (error) {
618 console.error(
619 `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}`,
620 )
621β
622 // Prevent the replaceEqualDeep from being called again down below.
623 throw error
624 }
625 }
626 // Structurally share data between prev and new data if needed
627 return replaceEqualDeep(prevData, data)
628 }
629 return data
630}
631β
632/**
633 * Intended to be passed as a query's `placeholderData` option, for example
634 * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new
635 * query key is fetching, it keeps displaying the previously fetched data until the new data arrives.
636 * @param previousData - The data of the previous query key, passed by the observer.
637 * @returns The previous data, unchanged.
638 * @example
639 * ```ts
640 * new QueryObserver(queryClient, {
641 * queryKey: ['posts', page],
642 * queryFn: () => fetchPosts(page),
643 * placeholderData: keepPreviousData,
644 * })
645 * ```
646 */
647export function keepPreviousData<T>(
648 previousData: T | undefined,
649): T | undefined {
650 return previousData
651}
652β
653/**
654 * Returns a new array with `item` added at the end. If that makes the array longer than `max`,
655 * the first item is dropped. Only one item is dropped, so the result can still exceed `max` if
656 * `items` already did.
657 * @param items - The current items.
658 * @param item - The value to append.
659 * @param max - The length above which an item is dropped. `0` (the default) means no limit.
660 * @returns A new array with `item` added.
661 */
662export function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {
663 const newItems = [...items, item]
664 return max && newItems.length > max ? newItems.slice(1) : newItems
665}
666β
667/**
668 * Returns a new array with `item` added at the start. If that makes the array longer than `max`,
669 * the last item is dropped. Only one item is dropped, so the result can still exceed `max` if
670 * `items` already did.
671 * @param items - The current items.
672 * @param item - The value to prepend.
673 * @param max - The length above which an item is dropped. `0` (the default) means no limit.
674 * @returns A new array with `item` added.
675 */
676export function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {
677 const newItems = [item, ...items]
678 return max && newItems.length > max ? newItems.slice(0, -1) : newItems
679}
680β
681/**
682 * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent
683 * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`,
684 * a query disabled via `skipToken` cannot be triggered with `refetch`.
685 * @example
686 * ```ts
687 * new QueryObserver(queryClient, {
688 * queryKey: ['post', postId],
689 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
690 * })
691 * ```
692 */
693export const skipToken = Symbol()
694/**
695 * The type of the {@link skipToken} sentinel value.
696 */
697export type SkipToken = typeof skipToken
698β
699/**
700 * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from
701 * an `initialPromise`, that promise is returned instead. If there is no usable `queryFn` (missing or
702 * {@link skipToken}), the returned function rejects with a `Missing queryFn` error.
703 * @param options - The query options with the `queryFn`, and the `queryHash` used in error messages.
704 * @param fetchOptions - The fetch options, which may carry an `initialPromise`.
705 * @returns The function to call for the fetch.
706 */
707export function ensureQueryFn<
708 TQueryFnData = unknown,
709 TQueryKey extends QueryKey = QueryKey,
710>(
711 options: {
712 queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken
713 queryHash?: string
714 },
715 fetchOptions?: FetchOptions<TQueryFnData>,
716): QueryFunction<TQueryFnData, TQueryKey> {
717 if (process.env.NODE_ENV !== 'production') {
718 if (options.queryFn === skipToken) {
719 console.error(
720 `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,
721 )
722 }
723 }
724β
725 // if we attempt to retry a fetch that was triggered from an initialPromise
726 // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise
727 // if an observer has already mounted, we will be able to retry with that queryFn
728 if (!options.queryFn && fetchOptions?.initialPromise) {
729 return () => fetchOptions.initialPromise!
730 }
731β
732 if (!options.queryFn || options.queryFn === skipToken) {
733 return () =>
734 Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))
735 }
736β
737 return options.queryFn
738}
739β
740/**
741 * Resolves a `throwOnError` option to a boolean.
742 * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller,
743 * additional context such as the query or mutation) and its result is returned, allowing the throwing
744 * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined`
745 * resolves to `false`).
746 * @param throwOnError - The `throwOnError` option: a boolean, a function that decides per error, or
747 * `undefined`.
748 * @param params - The arguments passed to `throwOnError` if it is a function.
749 * @returns Whether the error should be thrown.
750 * @example
751 * ```ts
752 * const throwOnError =
753 * query.state.error && typeof options.throwOnError === 'function'
754 * ? shouldThrowError(options.throwOnError, [query.state.error, query])
755 * : options.throwOnError
756 * ```
757 */
758export function shouldThrowError<T extends (...args: Array<any>) => boolean>(
759 throwOnError: boolean | T | undefined,
760 params: Parameters<T>,
761): boolean {
762 // Allow throwOnError function to override throwing behavior on a per-error basis
763 if (typeof throwOnError === 'function') {
764 return throwOnError(...params)
765 }
766β
767 return !!throwOnError
768}
769β
770/**
771 * Adds a lazy `signal` getter to an object, such as a query function context. The first time
772 * `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right
773 * away if it is already aborted), so cancellation is only tracked when the signal is actually used.
774 * @param object - The object to add the `signal` property to.
775 * @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read.
776 * @param onCancelled - Called when the signal is aborted, if `signal` was read.
777 * @returns The same object, with the `signal` property added.
778 */
779export function addConsumeAwareSignal<T>(
780 object: T,
781 getSignal: () => AbortSignal,
782 onCancelled: VoidFunction,
783): T & { signal: AbortSignal } {
784 let consumed = false
785 let signal: AbortSignal | undefined
786β
787 Object.defineProperty(object, 'signal', {
788 enumerable: true,
789 get: () => {
790 signal ??= getSignal()
791 if (consumed) {
792 return signal
793 }
794β
795 consumed = true
796 if (signal.aborted) {
797 onCancelled()
798 } else {
799 signal.addEventListener('abort', onCancelled, { once: true })
800 }
801β
802 return signal
803 },
804 })
805β
806 return object as T & { signal: AbortSignal }
807}