-
Notifications
You must be signed in to change notification settings - Fork 125
/
fetch.ts
232 lines (204 loc) · 6.81 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
import destr from "destr";
import { withBase, withQuery } from "ufo";
import type { Fetch, RequestInfo, RequestInit, Response } from "./types";
import { createFetchError } from "./error";
import {
isPayloadMethod,
isJSONSerializable,
detectResponseType,
ResponseType,
MappedType,
} from "./utils";
export interface CreateFetchOptions {
// eslint-disable-next-line no-use-before-define
defaults?: FetchOptions;
fetch: Fetch;
Headers: typeof Headers;
}
export type FetchRequest = RequestInfo;
export interface FetchResponse<T> extends Response {
_data?: T;
}
export interface SearchParameters {
[key: string]: any;
}
export interface FetchContext<T = any, R extends ResponseType = ResponseType> {
request: FetchRequest;
// eslint-disable-next-line no-use-before-define
options: FetchOptions<R>;
response?: FetchResponse<T>;
error?: Error;
}
export interface FetchOptions<R extends ResponseType = ResponseType>
extends Omit<RequestInit, "body"> {
baseURL?: string;
body?: RequestInit["body"] | Record<string, any>;
params?: SearchParameters;
query?: SearchParameters;
parseResponse?: (responseText: string) => any;
responseType?: R;
response?: boolean;
retry?: number | false;
onRequest?(context: FetchContext): Promise<void> | void;
onRequestError?(
context: FetchContext & { error: Error }
): Promise<void> | void;
onResponse?(
context: FetchContext & { response: FetchResponse<R> }
): Promise<void> | void;
onResponseError?(
context: FetchContext & { response: FetchResponse<R> }
): Promise<void> | void;
}
export interface $Fetch {
<T = any, R extends ResponseType = "json">(
request: FetchRequest,
options?: FetchOptions<R>
): Promise<MappedType<R, T>>;
raw<T = any, R extends ResponseType = "json">(
request: FetchRequest,
options?: FetchOptions<R>
): Promise<FetchResponse<MappedType<R, T>>>;
native: Fetch;
create(defaults: FetchOptions): $Fetch;
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
const retryStatusCodes = new Set([
408, // Request Timeout
409, // Conflict
425, // Too Early
429, // Too Many Requests
500, // Internal Server Error
502, // Bad Gateway
503, // Service Unavailable
504, // Gateway Timeout
]);
export function createFetch(globalOptions: CreateFetchOptions): $Fetch {
const { fetch, Headers } = globalOptions;
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") || 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 && retryStatusCodes.has(responseCode)) {
return $fetchRaw(context.request, {
...context.options,
retry: retries - 1,
});
}
}
// Throw normalized error
const error = createFetchError(
context.request,
context.error,
context.response
);
// 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(
_request,
_options = {}
) {
const context: FetchContext = {
request: _request,
options: { ...globalOptions.defaults, ..._options },
response: undefined,
error: undefined,
};
if (context.options.onRequest) {
await context.options.onRequest(context);
}
if (typeof context.request === "string") {
if (context.options.baseURL) {
context.request = withBase(context.request, context.options.baseURL);
}
if (context.options.query || context.options.params) {
context.request = withQuery(context.request, {
...context.options.params,
...context.options.query,
});
}
if (
context.options.body &&
isPayloadMethod(context.options.method) &&
isJSONSerializable(context.options.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.
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");
}
}
}
context.response = await fetch(
context.request,
context.options as RequestInit
).catch(async (error) => {
context.error = error;
if (context.options.onRequestError) {
await context.options.onRequestError(context as any);
}
return onError(context);
});
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`
if (responseType === "json") {
const data = await context.response.text();
const parseFunction = context.options.parseResponse || destr;
context.response._data = parseFunction(data);
} else if (responseType === "stream") {
context.response._data = context.response.body;
} else {
context.response._data = await context.response[responseType]();
}
if (context.options.onResponse) {
await context.options.onResponse(context as any);
}
if (context.response.status >= 400 && context.response.status < 600) {
if (context.options.onResponseError) {
await context.options.onResponseError(context as any);
}
return onError(context);
}
return context.response;
};
const $fetch = function $fetch(request, options) {
return $fetchRaw(request, options).then((r) => r._data);
} as $Fetch;
$fetch.raw = $fetchRaw;
$fetch.native = fetch;
$fetch.create = (defaultOptions = {}) =>
createFetch({
...globalOptions,
defaults: {
...globalOptions.defaults,
...defaultOptions,
},
});
return $fetch;
}