-
Notifications
You must be signed in to change notification settings - Fork 2k
/
fetcher.ts
145 lines (119 loc) · 4.26 KB
/
fetcher.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import NetworkError from './NetworkError.ts'
import ProgressTimeout from './ProgressTimeout.ts'
const noop = (): void => {}
export type FetcherOptions = {
/** The HTTP method to use for the request. Default is 'GET'. */
method?: string
/** The request payload, if any. Default is null. */
body?: Document | XMLHttpRequestBodyInit | null
/** Milliseconds between XMLHttpRequest upload progress events before the request is aborted. Default is 30000 ms. */
timeout?: number
/** Sets the withCredentials property of the XMLHttpRequest object. Default is false. */
withCredentials?: boolean
/** Sets the responseType property of the XMLHttpRequest object. Default is an empty string. */
responseType?: XMLHttpRequestResponseType
/** An object representing any headers to send with the request. */
headers?: Record<string, string>
/** The number of retry attempts to make if the request fails. Default is 3. */
retries?: number
/** Called before the request is made. */
onBeforeRequest?: (
xhr: XMLHttpRequest,
retryCount: number,
) => void | Promise<void>
/** Function for tracking upload progress. */
onUploadProgress?: (event: ProgressEvent) => void
/** A function to determine whether to retry the request. */
shouldRetry?: (xhr: XMLHttpRequest) => boolean
/** Called after the response has succeeded or failed but before the promise is resolved. */
onAfterResponse?: (
xhr: XMLHttpRequest,
retryCount: number,
) => void | Promise<void>
/** Called when no XMLHttpRequest upload progress events have been received for `timeout` ms. */
onTimeout?: (timeout: number) => void
/** Signal to abort the upload. */
signal?: AbortSignal
}
/**
* Fetches data from a specified URL using XMLHttpRequest, with optional retry functionality and progress tracking.
*
* @param url The URL to send the request to.
* @param options Optional settings for the fetch operation.
*/
export function fetcher(
url: string,
options: FetcherOptions = {},
): Promise<XMLHttpRequest> {
const {
body = null,
headers = {},
method = 'GET',
onBeforeRequest = noop,
onUploadProgress = noop,
shouldRetry = () => true,
onAfterResponse = noop,
onTimeout = noop,
responseType,
retries = 3,
signal = null,
timeout = 30_000,
withCredentials = false,
} = options
// 300 ms, 600 ms, 1200 ms, 2400 ms, 4800 ms
const delay = (attempt: number): number => 0.3 * 2 ** (attempt - 1) * 1000
const timer = new ProgressTimeout(timeout, onTimeout)
function requestWithRetry(retryCount = 0): Promise<XMLHttpRequest> {
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(method, url, true)
xhr.withCredentials = withCredentials
if (responseType) {
xhr.responseType = responseType
}
signal?.addEventListener('abort', () => {
xhr.abort()
// Using DOMException for abort errors aligns with
// the convention established by the Fetch API.
reject(new DOMException('Aborted', 'AbortError'))
})
xhr.onload = async () => {
await onAfterResponse(xhr, retryCount)
if (xhr.status >= 200 && xhr.status < 300) {
timer.done()
resolve(xhr)
} else if (shouldRetry(xhr) && retryCount < retries) {
setTimeout(() => {
requestWithRetry(retryCount + 1).then(resolve, reject)
}, delay(retryCount))
} else {
timer.done()
reject(new NetworkError(xhr.statusText, xhr))
}
}
xhr.onerror = () => {
if (shouldRetry(xhr) && retryCount < retries) {
setTimeout(() => {
requestWithRetry(retryCount + 1).then(resolve, reject)
}, delay(retryCount))
} else {
timer.done()
reject(new NetworkError(xhr.statusText, xhr))
}
}
xhr.upload.onprogress = (event: ProgressEvent) => {
timer.progress()
onUploadProgress(event)
}
if (headers) {
Object.keys(headers).forEach((key) => {
xhr.setRequestHeader(key, headers[key])
})
}
await onBeforeRequest(xhr, retryCount)
xhr.send(body)
})
}
return requestWithRetry()
}