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

retryer.ts

204 lines5.3 KB

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