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

query.ts

622 lines15.4 KB

1import {
2 getAbortController,
3 Updater,
4 functionalUpdate,
5 isValidTimeout,
6 noop,
7 replaceEqualDeep,
8 timeUntilStale,
9 ensureQueryKeyArray,
10} from './utils'
11import type {
12 InitialDataFunction,
13 QueryKey,
14 QueryOptions,
15 QueryStatus,
16 QueryFunctionContext,
17 EnsuredQueryKey,
18 QueryMeta,
19 CancelOptions,
20 SetDataOptions,
21} from './types'
22import type { QueryCache } from './queryCache'
23import type { QueryObserver } from './queryObserver'
24import { notifyManager } from './notifyManager'
25import { getLogger } from './logger'
26import { Retryer, isCancelledError } from './retryer'
27​
28// TYPES
29​
30interface QueryConfig<
31 TQueryFnData,
32 TError,
33 TData,
34 TQueryKey extends QueryKey = QueryKey
35> {
36 cache: QueryCache
37 queryKey: TQueryKey
38 queryHash: string
39 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
40 defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
41 state?: QueryState<TData, TError>
42 meta: QueryMeta | undefined
44​
45export interface QueryState<TData = unknown, TError = unknown> {
46 data: TData | undefined
47 dataUpdateCount: number
48 dataUpdatedAt: number
49 error: TError | null
50 errorUpdateCount: number
51 errorUpdatedAt: number
52 fetchFailureCount: number
53 fetchMeta: any
54 isFetching: boolean
55 isInvalidated: boolean
56 isPaused: boolean
57 status: QueryStatus
59​
60export interface FetchContext<
61 TQueryFnData,
62 TError,
63 TData,
64 TQueryKey extends QueryKey = QueryKey
65> {
66 fetchFn: () => unknown | Promise<unknown>
67 fetchOptions?: FetchOptions
68 options: QueryOptions<TQueryFnData, TError, TData, any>
69 queryKey: EnsuredQueryKey<TQueryKey>
70 state: QueryState<TData, TError>
71 meta: QueryMeta | undefined
73​
74export interface QueryBehavior<
75 TQueryFnData = unknown,
76 TError = unknown,
77 TData = TQueryFnData,
78 TQueryKey extends QueryKey = QueryKey
79> {
80 onFetch: (
81 context: FetchContext<TQueryFnData, TError, TData, TQueryKey>
82 ) => void
84​
85export interface FetchOptions {
86 cancelRefetch?: boolean
87 meta?: any
89​
90interface FailedAction {
91 type: 'failed'
93​
94interface FetchAction {
95 type: 'fetch'
96 meta?: any
98​
99interface SuccessAction<TData> {
100 data: TData | undefined
101 type: 'success'
102 dataUpdatedAt?: number
104​
105interface ErrorAction<TError> {
106 type: 'error'
107 error: TError
109​
110interface InvalidateAction {
111 type: 'invalidate'
113​
114interface PauseAction {
115 type: 'pause'
117​
118interface ContinueAction {
119 type: 'continue'
121​
122interface SetStateAction<TData, TError> {
123 type: 'setState'
124 state: QueryState<TData, TError>
125 setStateOptions?: SetStateOptions
127​
128export type Action<TData, TError> =
129 | ContinueAction
130 | ErrorAction<TError>
131 | FailedAction
132 | FetchAction
133 | InvalidateAction
134 | PauseAction
135 | SetStateAction<TData, TError>
136 | SuccessAction<TData>
137​
138export interface SetStateOptions {
139 meta?: any
141​
142// CLASS
143​
144export class Query<
145 TQueryFnData = unknown,
146 TError = unknown,
147 TData = TQueryFnData,
148 TQueryKey extends QueryKey = QueryKey
149> {
150 queryKey: TQueryKey
151 queryHash: string
152 options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
153 initialState: QueryState<TData, TError>
154 revertState?: QueryState<TData, TError>
155 state: QueryState<TData, TError>
156 cacheTime!: number
157 meta: QueryMeta | undefined
158​
159 private cache: QueryCache
160 private promise?: Promise<TData>
161 private gcTimeout?: number
162 private retryer?: Retryer<TData, TError>
163 private observers: QueryObserver<any, any, any, any, any>[]
164 private defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
165 private abortSignalConsumed: boolean
166​
167 constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {
168 this.abortSignalConsumed = false
169 this.defaultOptions = config.defaultOptions
170 this.setOptions(config.options)
171 this.observers = []
172 this.cache = config.cache
173 this.queryKey = config.queryKey
174 this.queryHash = config.queryHash
175 this.initialState = config.state || this.getDefaultState(this.options)
176 this.state = this.initialState
177 this.meta = config.meta
178 this.scheduleGc()
179 }
180​
181 private setOptions(
182 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
183 ): void {
184 this.options = { ...this.defaultOptions, ...options }
185​
186 this.meta = options?.meta
187​
188 // Default to 5 minutes if not cache time is set
189 this.cacheTime = Math.max(
190 this.cacheTime || 0,
191 this.options.cacheTime ?? 5 * 60 * 1000
192 )
193 }
194​
195 setDefaultOptions(
196 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
197 ): void {
198 this.defaultOptions = options
199 }
200​
201 private scheduleGc(): void {
202 this.clearGcTimeout()
203​
204 if (isValidTimeout(this.cacheTime)) {
205 this.gcTimeout = setTimeout(() => {
206 this.optionalRemove()
207 }, this.cacheTime)
208 }
209 }
210​
211 private clearGcTimeout() {
212 clearTimeout(this.gcTimeout)
213 this.gcTimeout = undefined
214 }
215​
216 private optionalRemove() {
217 if (!this.observers.length && !this.state.isFetching) {
218 this.cache.remove(this)
219 }
220 }
221​
222 setData(
223 updater: Updater<TData | undefined, TData>,
224 options?: SetDataOptions
225 ): TData {
226 const prevData = this.state.data
227​
228 // Get the new data
229 let data = functionalUpdate(updater, prevData)
230​
231 // Use prev data if an isDataEqual function is defined and returns `true`
232 if (this.options.isDataEqual?.(prevData, data)) {
233 data = prevData as TData
234 } else if (this.options.structuralSharing !== false) {
235 // Structurally share data between prev and new data if needed
236 data = replaceEqualDeep(prevData, data)
237 }
238​
239 // Set data and mark it as cached
240 this.dispatch({
241 data,
242 type: 'success',
243 dataUpdatedAt: options?.updatedAt,
244 })
245​
246 return data
247 }
248​
249 setState(
250 state: QueryState<TData, TError>,
251 setStateOptions?: SetStateOptions
252 ): void {
253 this.dispatch({ type: 'setState', state, setStateOptions })
254 }
255​
256 cancel(options?: CancelOptions): Promise<void> {
257 const promise = this.promise
258 this.retryer?.cancel(options)
259 return promise ? promise.then(noop).catch(noop) : Promise.resolve()
260 }
261​
262 destroy(): void {
263 this.clearGcTimeout()
264 this.cancel({ silent: true })
265 }
266​
267 reset(): void {
268 this.destroy()
269 this.setState(this.initialState)
270 }
271​
272 isActive(): boolean {
273 return this.observers.some(observer => observer.options.enabled !== false)
274 }
275​
276 isFetching(): boolean {
277 return this.state.isFetching
278 }
279​
280 isStale(): boolean {
281 return (
282 this.state.isInvalidated ||
283 !this.state.dataUpdatedAt ||
284 this.observers.some(observer => observer.getCurrentResult().isStale)
285 )
286 }
287​
288 isStaleByTime(staleTime = 0): boolean {
289 return (
290 this.state.isInvalidated ||
291 !this.state.dataUpdatedAt ||
292 !timeUntilStale(this.state.dataUpdatedAt, staleTime)
293 )
294 }
295​
296 onFocus(): void {
297 const observer = this.observers.find(x => x.shouldFetchOnWindowFocus())
298​
299 if (observer) {
300 observer.refetch()
301 }
302​
303 // Continue fetch if currently paused
304 this.retryer?.continue()
305 }
306​
307 onOnline(): void {
308 const observer = this.observers.find(x => x.shouldFetchOnReconnect())
309​
310 if (observer) {
311 observer.refetch()
312 }
313​
314 // Continue fetch if currently paused
315 this.retryer?.continue()
316 }
317​
318 addObserver(observer: QueryObserver<any, any, any, any, any>): void {
319 if (this.observers.indexOf(observer) === -1) {
320 this.observers.push(observer)
321​
322 // Stop the query from being garbage collected
323 this.clearGcTimeout()
324​
325 this.cache.notify({ type: 'observerAdded', query: this, observer })
326 }
327 }
328​
329 removeObserver(observer: QueryObserver<any, any, any, any, any>): void {
330 if (this.observers.indexOf(observer) !== -1) {
331 this.observers = this.observers.filter(x => x !== observer)
332​
333 if (!this.observers.length) {
334 // If the transport layer does not support cancellation
335 // we'll let the query continue so the result can be cached
336 if (this.retryer) {
337 if (this.retryer.isTransportCancelable || this.abortSignalConsumed) {
338 this.retryer.cancel({ revert: true })
339 } else {
340 this.retryer.cancelRetry()
341 }
342 }
343​
344 if (this.cacheTime) {
345 this.scheduleGc()
346 } else {
347 this.cache.remove(this)
348 }
349 }
350​
351 this.cache.notify({ type: 'observerRemoved', query: this, observer })
352 }
353 }
354​
355 getObserversCount(): number {
356 return this.observers.length
357 }
358​
359 invalidate(): void {
360 if (!this.state.isInvalidated) {
361 this.dispatch({ type: 'invalidate' })
362 }
363 }
364​
365 fetch(
366 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
367 fetchOptions?: FetchOptions
368 ): Promise<TData> {
369 if (this.state.isFetching) {
370 if (this.state.dataUpdatedAt && fetchOptions?.cancelRefetch) {
371 // Silently cancel current fetch if the user wants to cancel refetches
372 this.cancel({ silent: true })
373 } else if (this.promise) {
374 // Return current promise if we are already fetching
375 return this.promise
376 }
377 }
378​
379 // Update config if passed, otherwise the config from the last execution is used
380 if (options) {
381 this.setOptions(options)
382 }
383​
384 // Use the options from the first observer with a query function if no function is found.
385 // This can happen when the query is hydrated or created with setQueryData.
386 if (!this.options.queryFn) {
387 const observer = this.observers.find(x => x.options.queryFn)
388 if (observer) {
389 this.setOptions(observer.options)
390 }
391 }
392​
393 const queryKey = ensureQueryKeyArray(this.queryKey)
394 const abortController = getAbortController()
395​
396 // Create query function context
397 const queryFnContext: QueryFunctionContext<TQueryKey> = {
398 queryKey,
399 pageParam: undefined,
400 meta: this.meta,
401 }
402​
403 Object.defineProperty(queryFnContext, 'signal', {
404 enumerable: true,
405 get: () => {
406 if (abortController) {
407 this.abortSignalConsumed = true
408 return abortController.signal
409 }
410 return undefined
411 },
412 })
413​
414 // Create fetch function
415 const fetchFn = () => {
416 if (!this.options.queryFn) {
417 return Promise.reject('Missing queryFn')
418 }
419 this.abortSignalConsumed = false
420 return this.options.queryFn(queryFnContext)
421 }
422​
423 // Trigger behavior hook
424 const context: FetchContext<TQueryFnData, TError, TData, TQueryKey> = {
425 fetchOptions,
426 options: this.options,
427 queryKey: queryKey,
428 state: this.state,
429 fetchFn,
430 meta: this.meta,
431 }
432​
433 if (this.options.behavior?.onFetch) {
434 this.options.behavior?.onFetch(context)
435 }
436​
437 // Store state in case the current fetch needs to be reverted
438 this.revertState = this.state
439​
440 // Set to fetching state if not already in it
441 if (
442 !this.state.isFetching ||
443 this.state.fetchMeta !== context.fetchOptions?.meta
444 ) {
445 this.dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })
446 }
447​
448 // Try to fetch the data
449 this.retryer = new Retryer({
450 fn: context.fetchFn as () => TData,
451 abort: abortController?.abort?.bind(abortController),
452 onSuccess: data => {
453 this.setData(data as TData)
454​
455 // Notify cache callback
456 this.cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
457​
458 // Remove query after fetching if cache time is 0
459 if (this.cacheTime === 0) {
460 this.optionalRemove()
461 }
462 },
463 onError: (error: TError | { silent?: boolean }) => {
464 // Optimistically update state if needed
465 if (!(isCancelledError(error) && error.silent)) {
466 this.dispatch({
467 type: 'error',
468 error: error as TError,
469 })
470 }
471​
472 if (!isCancelledError(error)) {
473 // Notify cache callback
474 this.cache.config.onError?.(error, this as Query<any, any, any, any>)
475​
476 // Log error
477 getLogger().error(error)
478 }
479​
480 // Remove query after fetching if cache time is 0
481 if (this.cacheTime === 0) {
482 this.optionalRemove()
483 }
484 },
485 onFail: () => {
486 this.dispatch({ type: 'failed' })
487 },
488 onPause: () => {
489 this.dispatch({ type: 'pause' })
490 },
491 onContinue: () => {
492 this.dispatch({ type: 'continue' })
493 },
494 retry: context.options.retry,
495 retryDelay: context.options.retryDelay,
496 })
497​
498 this.promise = this.retryer.promise
499​
500 return this.promise
501 }
502​
503 private dispatch(action: Action<TData, TError>): void {
504 this.state = this.reducer(this.state, action)
505​
506 notifyManager.batch(() => {
507 this.observers.forEach(observer => {
508 observer.onQueryUpdate(action)
509 })
510​
511 this.cache.notify({ query: this, type: 'queryUpdated', action })
512 })
513 }
514​
515 protected getDefaultState(
516 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
517 ): QueryState<TData, TError> {
518 const data =
519 typeof options.initialData === 'function'
520 ? (options.initialData as InitialDataFunction<TData>)()
521 : options.initialData
522​
523 const hasInitialData = typeof options.initialData !== 'undefined'
524​
525 const initialDataUpdatedAt = hasInitialData
526 ? typeof options.initialDataUpdatedAt === 'function'
527 ? (options.initialDataUpdatedAt as () => number | undefined)()
528 : options.initialDataUpdatedAt
529 : 0
530​
531 const hasData = typeof data !== 'undefined'
532​
533 return {
534 data,
535 dataUpdateCount: 0,
536 dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
537 error: null,
538 errorUpdateCount: 0,
539 errorUpdatedAt: 0,
540 fetchFailureCount: 0,
541 fetchMeta: null,
542 isFetching: false,
543 isInvalidated: false,
544 isPaused: false,
545 status: hasData ? 'success' : 'idle',
546 }
547 }
548​
549 protected reducer(
550 state: QueryState<TData, TError>,
551 action: Action<TData, TError>
552 ): QueryState<TData, TError> {
553 switch (action.type) {
554 case 'failed':
555 return {
556 ...state,
557 fetchFailureCount: state.fetchFailureCount + 1,
558 }
559 case 'pause':
560 return {
561 ...state,
562 isPaused: true,
563 }
564 case 'continue':
565 return {
566 ...state,
567 isPaused: false,
568 }
569 case 'fetch':
570 return {
571 ...state,
572 fetchFailureCount: 0,
573 fetchMeta: action.meta ?? null,
574 isFetching: true,
575 isPaused: false,
576 status: !state.dataUpdatedAt ? 'loading' : state.status,
577 }
578 case 'success':
579 return {
580 ...state,
581 data: action.data,
582 dataUpdateCount: state.dataUpdateCount + 1,
583 dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
584 error: null,
585 fetchFailureCount: 0,
586 isFetching: false,
587 isInvalidated: false,
588 isPaused: false,
589 status: 'success',
590 }
591 case 'error':
592 const error = action.error as unknown
593​
594 if (isCancelledError(error) && error.revert && this.revertState) {
595 return { ...this.revertState }
596 }
597​
598 return {
599 ...state,
600 error: error as TError,
601 errorUpdateCount: state.errorUpdateCount + 1,
602 errorUpdatedAt: Date.now(),
603 fetchFailureCount: state.fetchFailureCount + 1,
604 isFetching: false,
605 isPaused: false,
606 status: 'error',
607 }
608 case 'invalidate':
609 return {
610 ...state,
611 isInvalidated: true,
612 }
613 case 'setState':
614 return {
615 ...state,
616 ...action.state,
617 }
618 default:
619 return state
620 }
621 }