-
Notifications
You must be signed in to change notification settings - Fork 127
/
fetch.ts
284 lines (258 loc) · 8.65 KB
/
fetch.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import type { Readable } from "node:stream";
import destr from "destr";
import { withBase, withQuery } from "ufo";
import { createFetchError } from "./error";
import {
isPayloadMethod,
isJSONSerializable,
detectResponseType,
resolveFetchOptions,
callHooks,
} from "./utils";
import type {
CreateFetchOptions,
FetchResponse,
ResponseType,
FetchContext,
$Fetch,
FetchRequest,
FetchOptions,
} from "./types";
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
const retryStatusCodes = new Set([
408, // Request Timeout
409, // Conflict
425, // Too Early (Experimental)
429, // Too Many Requests
500, // Internal Server Error
502, // Bad Gateway
503, // Service Unavailable
504, // Gateway Timeout
]);
// https://developer.mozilla.org/en-US/docs/Web/API/Response/body
const nullBodyResponses = new Set([101, 204, 205, 304]);
export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
const {
fetch = globalThis.fetch,
Headers = globalThis.Headers,
AbortController = globalThis.AbortController,
} = globalOptions;
async function onError(context: FetchContext): Promise<FetchResponse<any>> {
// Is Abort
// If it is an active abort, it will not retry automatically.
// https://developer.mozilla.org/en-US/docs/Web/API/DOMException#error_names
const isAbort =
(context.error &&
context.error.name === "AbortError" &&
!context.options.timeout) ||
false;
// Retry
if (context.options.retry !== false && !isAbort) {
let retries;
if (typeof context.options.retry === "number") {
retries = context.options.retry;
} else {
retries = isPayloadMethod(context.options.method) ? 0 : 1;
}
const responseCode = (context.response && context.response.status) || 500;
if (
retries > 0 &&
(Array.isArray(context.options.retryStatusCodes)
? context.options.retryStatusCodes.includes(responseCode)
: retryStatusCodes.has(responseCode))
) {
const retryDelay =
typeof context.options.retryDelay === "function"
? context.options.retryDelay(context)
: context.options.retryDelay || 0;
if (retryDelay > 0) {
await new Promise((resolve) => setTimeout(resolve, retryDelay));
}
// Timeout
return $fetchRaw(context.request, {
...context.options,
retry: retries - 1,
});
}
}
// Throw normalized error
const error = createFetchError(context);
// Only available on V8 based runtimes (https://v8.dev/docs/stack-trace-api)
if (Error.captureStackTrace) {
Error.captureStackTrace(error, $fetchRaw);
}
throw error;
}
const $fetchRaw: $Fetch["raw"] = async function $fetchRaw<
T = any,
R extends ResponseType = "json",
>(_request: FetchRequest, _options: FetchOptions<R> = {}) {
const context: FetchContext = {
request: _request,
options: resolveFetchOptions<R, T>(
_request,
_options,
globalOptions.defaults as unknown as FetchOptions<R, T>,
Headers
),
response: undefined,
error: undefined,
};
// Uppercase method name
if (context.options.method) {
context.options.method = context.options.method.toUpperCase();
}
if (context.options.onRequest) {
await callHooks(context, context.options.onRequest);
}
if (typeof context.request === "string") {
if (context.options.baseURL) {
context.request = withBase(context.request, context.options.baseURL);
}
if (context.options.query) {
context.request = withQuery(context.request, context.options.query);
delete context.options.query;
}
if ("query" in context.options) {
delete context.options.query;
}
if ("params" in context.options) {
delete context.options.params;
}
}
if (context.options.body && isPayloadMethod(context.options.method)) {
if (isJSONSerializable(context.options.body)) {
// JSON Body
// Automatically JSON stringify request bodies, when not already a string.
context.options.body =
typeof context.options.body === "string"
? context.options.body
: JSON.stringify(context.options.body);
// Set Content-Type and Accept headers to application/json by default
// for JSON serializable request bodies.
// Pass empty object as older browsers don't support undefined.
context.options.headers = new Headers(context.options.headers || {});
if (!context.options.headers.has("content-type")) {
context.options.headers.set("content-type", "application/json");
}
if (!context.options.headers.has("accept")) {
context.options.headers.set("accept", "application/json");
}
} else if (
// ReadableStream Body
("pipeTo" in (context.options.body as ReadableStream) &&
typeof (context.options.body as ReadableStream).pipeTo ===
"function") ||
// Node.js Stream Body
typeof (context.options.body as Readable).pipe === "function"
) {
// eslint-disable-next-line unicorn/no-lonely-if
if (!("duplex" in context.options)) {
context.options.duplex = "half";
}
}
}
let abortTimeout: NodeJS.Timeout | undefined;
// TODO: Can we merge signals?
if (!context.options.signal && context.options.timeout) {
const controller = new AbortController();
abortTimeout = setTimeout(() => {
const error = new Error(
"[TimeoutError]: The operation was aborted due to timeout"
);
error.name = "TimeoutError";
(error as any).code = 23; // DOMException.TIMEOUT_ERR
controller.abort(error);
}, context.options.timeout);
context.options.signal = controller.signal;
}
try {
context.response = await fetch(
context.request,
context.options as RequestInit
);
} catch (error) {
context.error = error as Error;
if (context.options.onRequestError) {
await callHooks(
context as FetchContext & { error: Error },
context.options.onRequestError
);
}
return await onError(context);
} finally {
if (abortTimeout) {
clearTimeout(abortTimeout);
}
}
const hasBody =
(context.response.body ||
// https://github.com/unjs/ofetch/issues/324
// https://github.com/unjs/ofetch/issues/294
// https://github.com/JakeChampion/fetch/issues/1454
(context.response as any)._bodyInit) &&
!nullBodyResponses.has(context.response.status) &&
context.options.method !== "HEAD";
if (hasBody) {
const responseType =
(context.options.parseResponse
? "json"
: context.options.responseType) ||
detectResponseType(context.response.headers.get("content-type") || "");
// We override the `.json()` method to parse the body more securely with `destr`
switch (responseType) {
case "json": {
const data = await context.response.text();
const parseFunction = context.options.parseResponse || destr;
context.response._data = parseFunction(data);
break;
}
case "stream": {
context.response._data =
context.response.body || (context.response as any)._bodyInit; // (see refs above)
break;
}
default: {
context.response._data = await context.response[responseType]();
}
}
}
if (context.options.onResponse) {
await callHooks(
context as FetchContext & { response: FetchResponse<any> },
context.options.onResponse
);
}
if (
!context.options.ignoreResponseError &&
context.response.status >= 400 &&
context.response.status < 600
) {
if (context.options.onResponseError) {
await callHooks(
context as FetchContext & { response: FetchResponse<any> },
context.options.onResponseError
);
}
return await onError(context);
}
return context.response;
};
const $fetch = async function $fetch(request, options) {
const r = await $fetchRaw(request, options);
return r._data;
} as $Fetch;
$fetch.raw = $fetchRaw;
$fetch.native = (...args) => fetch(...args);
$fetch.create = (defaultOptions = {}, customGlobalOptions = {}) =>
createFetch({
...globalOptions,
...customGlobalOptions,
defaults: {
...globalOptions.defaults,
...customGlobalOptions.defaults,
...defaultOptions,
},
});
return $fetch;
}