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

retryer.ts

212 lines5.5 KB

1import { focusManager } from './focusManager'
2import { onlineManager } from './onlineManager'
3import { sleep } from './utils'
4import { CancelOptions } from './types'
5​
6// TYPES
7​
8interface RetryerConfig<TData = unknown, TError = unknown> {
9 fn: () => TData | Promise<TData>
10 abort?: () => void
11 onError?: (error: TError) => void
12 onSuccess?: (data: TData) => void
13 onFail?: (failureCount: number, error: TError) => void
14 onPause?: () => void
15 onContinue?: () => void
16 retry?: RetryValue<TError>
17 retryDelay?: RetryDelayValue<TError>
19​
20export type RetryValue<TError> = boolean | number | ShouldRetryFunction<TError>
21​
22type ShouldRetryFunction<TError = unknown> = (
23 failureCount: number,
24 error: TError
25) => boolean
26​
27export type RetryDelayValue<TError> = number | RetryDelayFunction<TError>
28​
29type RetryDelayFunction<TError = unknown> = (
30 failureCount: number,
31 error: TError
32) => number
33​
34function defaultRetryDelay(failureCount: number) {
35 return Math.min(1000 * 2 ** failureCount, 30000)
37​
38interface Cancelable {
39 cancel(): void
41​
42export function isCancelable(value: any): value is Cancelable {
43 return typeof value?.cancel === 'function'
45​
46export class CancelledError {
47 revert?: boolean
48 silent?: boolean
49 constructor(options?: CancelOptions) {
50 this.revert = options?.revert
51 this.silent = options?.silent
52 }
54​
55export function isCancelledError(value: any): value is CancelledError {
56 return value instanceof CancelledError
58​
59// CLASS
60​
61export class Retryer<TData = unknown, TError = unknown> {
62 cancel: (options?: CancelOptions) => void
63 cancelRetry: () => void
64 continue: () => void
65 failureCount: number
66 isPaused: boolean
67 isResolved: boolean
68 isTransportCancelable: boolean
69 promise: Promise<TData>
70​
71 private abort?: () => void
72​
73 constructor(config: RetryerConfig<TData, TError>) {
74 let cancelRetry = false
75 let cancelFn: ((options?: CancelOptions) => void) | undefined
76 let continueFn: ((value?: unknown) => void) | undefined
77 let promiseResolve: (data: TData) => void
78 let promiseReject: (error: TError) => void
79​
80 this.abort = config.abort
81 this.cancel = cancelOptions => cancelFn?.(cancelOptions)
82 this.cancelRetry = () => {
83 cancelRetry = true
84 }
85 this.continue = () => continueFn?.()
86 this.failureCount = 0
87 this.isPaused = false
88 this.isResolved = false
89 this.isTransportCancelable = false
90 this.promise = new Promise<TData>((outerResolve, outerReject) => {
91 promiseResolve = outerResolve
92 promiseReject = outerReject
93 })
94​
95 const resolve = (value: any) => {
96 if (!this.isResolved) {
97 this.isResolved = true
98 config.onSuccess?.(value)
99 continueFn?.()
100 promiseResolve(value)
101 }
102 }
103​
104 const reject = (value: any) => {
105 if (!this.isResolved) {
106 this.isResolved = true
107 config.onError?.(value)
108 continueFn?.()
109 promiseReject(value)
110 }
111 }
112​
113 const pause = () => {
114 return new Promise(continueResolve => {
115 continueFn = continueResolve
116 this.isPaused = true
117 config.onPause?.()
118 }).then(() => {
119 continueFn = undefined
120 this.isPaused = false
121 config.onContinue?.()
122 })
123 }
124​
125 // Create loop function
126 const run = () => {
127 // Do nothing if already resolved
128 if (this.isResolved) {
129 return
130 }
131​
132 let promiseOrValue: any
133​
134 // Execute query
135 try {
136 promiseOrValue = config.fn()
137 } catch (error) {
138 promiseOrValue = Promise.reject(error)
139 }
140​
141 // Create callback to cancel this fetch
142 cancelFn = cancelOptions => {
143 if (!this.isResolved) {
144 reject(new CancelledError(cancelOptions))
145​
146 this.abort?.()
147​
148 // Cancel transport if supported
149 if (isCancelable(promiseOrValue)) {
150 try {
151 promiseOrValue.cancel()
152 } catch {}
153 }
154 }
155 }
156​
157 // Check if the transport layer support cancellation
158 this.isTransportCancelable = isCancelable(promiseOrValue)
159​
160 Promise.resolve(promiseOrValue)
161 .then(resolve)
162 .catch(error => {
163 // Stop if the fetch is already resolved
164 if (this.isResolved) {
165 return
166 }
167​
168 // Do we need to retry the request?
169 const retry = config.retry ?? 3
170 const retryDelay = config.retryDelay ?? defaultRetryDelay
171 const delay =
172 typeof retryDelay === 'function'
173 ? retryDelay(this.failureCount, error)
174 : retryDelay
175 const shouldRetry =
176 retry === true ||
177 (typeof retry === 'number' && this.failureCount < retry) ||
178 (typeof retry === 'function' && retry(this.failureCount, error))
179​
180 if (cancelRetry || !shouldRetry) {
181 // We are done if the query does not need to be retried
182 reject(error)
183 return
184 }
185​
186 this.failureCount++
187​
188 // Notify on fail
189 config.onFail?.(this.failureCount, error)
190​
191 // Delay
192 sleep(delay)
193 // Pause if the document is not visible or when the device is offline
194 .then(() => {
195 if (!focusManager.isFocused() || !onlineManager.isOnline()) {
196 return pause()
197 }
198 })
199 .then(() => {
200 if (cancelRetry) {
201 reject(error)
202 } else {
203 run()
204 }
205 })
206 })
207 }
208​
209 // Start loop
210 run()
211 }