-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathfetch.ts
259 lines (238 loc) · 8.1 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
/**
* A basic Fetch Handler which converts a request into a
* `fetch` call presuming the response to be `json`.
*
* ```ts
* import Fetch from '@ember-data/request/fetch';
*
* manager.use([Fetch]);
* ```
*
* @module @ember-data/request/fetch
* @main @ember-data/request/fetch
*/
import { DEBUG } from '@warp-drive/build-config/env';
import { cloneResponseProperties, type Context } from './-private/context';
import type { HttpErrorProps } from './-private/utils';
// Lazily close over fetch to avoid breaking Mirage
const _fetch: typeof fetch =
typeof fetch !== 'undefined'
? (...args) => fetch(...args)
: typeof FastBoot !== 'undefined'
? (...args) => (FastBoot.require('node-fetch') as typeof fetch)(...args)
: ((() => {
throw new Error('No Fetch Implementation Found');
}) as typeof fetch);
// clones a response in a way that should still
// allow it to stream
function cloneResponse(response: Response, overrides: Partial<Response>) {
const props = cloneResponseProperties(response);
return new Response(response.body, Object.assign(props, overrides));
}
let IS_MAYBE_MIRAGE = () => false;
if (DEBUG) {
IS_MAYBE_MIRAGE = () =>
Boolean(
typeof window !== 'undefined' &&
((window as { server?: { pretender: unknown } }).server?.pretender ||
window.fetch.toString().replace(/\s+/g, '') !== 'function fetch() { [native code] }'.replace(/\s+/g, ''))
);
}
const MUTATION_OPS = new Set(['updateRecord', 'createRecord', 'deleteRecord']);
const ERROR_STATUS_CODE_FOR = new Map([
[400, 'Bad Request'],
[401, 'Unauthorized'],
[402, 'Payment Required'],
[403, 'Forbidden'],
[404, 'Not Found'],
[405, 'Method Not Allowed'],
[406, 'Not Acceptable'],
[407, 'Proxy Authentication Required'],
[408, 'Request Timeout'],
[409, 'Conflict'],
[410, 'Gone'],
[411, 'Length Required'],
[412, 'Precondition Failed'],
[413, 'Payload Too Large'],
[414, 'URI Too Long'],
[415, 'Unsupported Media Type'],
[416, 'Range Not Satisfiable'],
[417, 'Expectation Failed'],
[419, 'Page Expired'],
[420, 'Enhance Your Calm'],
[421, 'Misdirected Request'],
[422, 'Unprocessable Entity'],
[423, 'Locked'],
[424, 'Failed Dependency'],
[425, 'Too Early'],
[426, 'Upgrade Required'],
[428, 'Precondition Required'],
[429, 'Too Many Requests'],
[430, 'Request Header Fields Too Large'],
[431, 'Request Header Fields Too Large'],
[450, 'Blocked By Windows Parental Controls'],
[451, 'Unavailable For Legal Reasons'],
[500, 'Internal Server Error'],
[501, 'Not Implemented'],
[502, 'Bad Gateway'],
[503, 'Service Unavailable'],
[504, 'Gateway Timeout'],
[505, 'HTTP Version Not Supported'],
[506, 'Variant Also Negotiates'],
[507, 'Insufficient Storage'],
[508, 'Loop Detected'],
[509, 'Bandwidth Limit Exceeded'],
[510, 'Not Extended'],
[511, 'Network Authentication Required'],
]);
/**
* A basic handler which converts a request into a
* `fetch` call presuming the response to be `json`.
*
* ```ts
* import Fetch from '@ember-data/request/fetch';
*
* manager.use([Fetch]);
* ```
*
* @class Fetch
* @public
*/
const Fetch = {
async request<T>(context: Context): Promise<T> {
let response: Response;
try {
response = await _fetch(context.request.url!, context.request);
} catch (e) {
if (e instanceof DOMException && e.name === 'AbortError') {
(e as unknown as HttpErrorProps).statusText = 'Aborted';
(e as unknown as HttpErrorProps).status = 20;
(e as unknown as HttpErrorProps).isRequestError = true;
} else {
(e as HttpErrorProps).statusText = 'Unknown Network Error';
(e as HttpErrorProps).status = 0;
(e as HttpErrorProps).isRequestError = true;
}
throw e;
}
const isError = !response.ok || response.status >= 400;
const op = context.request.op;
const isMutationOp = Boolean(op && MUTATION_OPS.has(op));
if (!isError && !isMutationOp && response.status !== 204 && !response.headers.has('date')) {
if (IS_MAYBE_MIRAGE()) {
response.headers.set('date', new Date().toUTCString());
} else {
const headers = new Headers(response.headers);
headers.set('date', new Date().toUTCString());
response = cloneResponse(response, {
headers,
});
}
}
context.setResponse(response);
if (response.status === 204) {
return null as T;
}
let text = '';
// if we are in a mirage context, we cannot support streaming
if (IS_MAYBE_MIRAGE()) {
text = await response.text();
} else {
const reader = response.body!.getReader();
const decoder = new TextDecoder();
let isStreaming = context.hasRequestedStream;
let stream: TransformStream | null = isStreaming ? new TransformStream() : null;
let writer = stream?.writable.getWriter();
if (isStreaming) {
// Listen for the abort event on the AbortSignal
context.request.signal?.addEventListener('abort', () => {
if (!isStreaming) {
return;
}
void stream!.writable.abort('Request Aborted');
void stream!.readable.cancel('Request Aborted');
});
context.setStream(stream!.readable);
}
while (true) {
// we manually read the stream instead of using `response.json()`
// or `response.text()` because if we need to stream the body
// we need to be able to pass the stream along efficiently.
const { done, value } = await reader.read();
if (done) {
if (isStreaming) {
isStreaming = false;
await writer!.ready;
await writer!.close();
}
break;
}
text += decoder.decode(value, { stream: true });
// if we are streaming, we want to pass the stream along
if (isStreaming) {
await writer!.ready;
await writer!.write(value);
} else if (context.hasRequestedStream) {
const encode = new TextEncoder();
isStreaming = true;
stream = new TransformStream();
// Listen for the abort event on the AbortSignal
// eslint-disable-next-line @typescript-eslint/no-loop-func
context.request.signal?.addEventListener('abort', () => {
if (!isStreaming) {
return;
}
void stream!.writable.abort('Request Aborted');
void stream!.readable.cancel('Request Aborted');
});
context.setStream(stream.readable);
writer = stream.writable.getWriter();
await writer.ready;
await writer.write(encode.encode(text));
await writer.ready;
await writer.write(value);
}
}
if (isStreaming) {
isStreaming = false;
await writer!.ready;
await writer!.close();
}
}
// if we are an error, we will want to throw
if (isError) {
let errorPayload: object | undefined;
try {
errorPayload = JSON.parse(text) as object;
} catch {
// void;
}
// attempt errors discovery
const errors = Array.isArray(errorPayload)
? errorPayload
: isDict(errorPayload) && Array.isArray(errorPayload.errors)
? errorPayload.errors
: null;
const statusText = response.statusText || ERROR_STATUS_CODE_FOR.get(response.status) || 'Unknown Request Error';
const msg = `[${response.status} ${statusText}] ${context.request.method ?? 'GET'} (${response.type}) - ${
response.url
}`;
const error = (errors ? new AggregateError(errors, msg) : new Error(msg)) as Error & {
content: object | undefined;
} & HttpErrorProps;
error.status = response.status;
error.statusText = statusText;
error.isRequestError = true;
error.code = error.status;
error.name = error.statusText.replaceAll(' ', '') + 'Error';
error.content = errorPayload;
throw error;
} else {
return JSON.parse(text) as T;
}
},
};
function isDict(v: unknown): v is Record<string, unknown> {
return v !== null && typeof v === 'object';
}
export default Fetch;