-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathfetchHttpClient.ts
256 lines (225 loc) · 8.19 KB
/
fetchHttpClient.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
import AbortController from "abort-controller";
import FormData from "form-data";
import { HttpClient } from "./httpClient";
import { WebResourceLike } from "./webResource";
import { HttpOperationResponse } from "./httpOperationResponse";
import { HttpHeaders, HttpHeadersLike } from "./httpHeaders";
import { RestError } from "./restError";
import { Readable, Transform } from "stream";
interface FetchError extends Error {
code?: string;
errno?: string;
type?: string;
}
export type CommonRequestInfo = string; // we only call fetch() on string urls.
export type CommonRequestInit = Omit<RequestInit, "body" | "headers" | "signal"> & {
body?: any;
headers?: any;
signal?: any;
};
export type CommonResponse = Omit<Response, "body" | "trailer" | "formData"> & {
body: any;
trailer: any;
formData: any;
};
export abstract class FetchHttpClient implements HttpClient {
async sendRequest(httpRequest: WebResourceLike): Promise<HttpOperationResponse> {
if (!httpRequest && typeof httpRequest !== "object") {
throw new Error(
"'httpRequest' (WebResource) cannot be null or undefined and must be of type object."
);
}
const abortController = new AbortController();
let abortListener: ((event: any) => void) | undefined;
if (httpRequest.abortSignal) {
if (httpRequest.abortSignal.aborted) {
throw new RestError(
"The request was aborted",
RestError.REQUEST_ABORTED_ERROR,
undefined,
httpRequest
);
}
abortListener = (event: Event) => {
if (event.type === "abort") {
abortController.abort();
}
};
httpRequest.abortSignal.addEventListener("abort", abortListener);
}
if (httpRequest.timeout) {
setTimeout(() => {
abortController.abort();
}, httpRequest.timeout);
}
if (httpRequest.formData) {
const formData: any = httpRequest.formData;
const requestForm = new FormData();
const appendFormValue = (key: string, value: any) => {
// value function probably returns a stream so we can provide a fresh stream on each retry
if (typeof value === "function") {
value = value();
}
if (value && value.hasOwnProperty("value") && value.hasOwnProperty("options")) {
requestForm.append(key, value.value, value.options);
} else {
requestForm.append(key, value);
}
};
for (const formKey of Object.keys(formData)) {
const formValue = formData[formKey];
if (Array.isArray(formValue)) {
for (let j = 0; j < formValue.length; j++) {
appendFormValue(formKey, formValue[j]);
}
} else {
appendFormValue(formKey, formValue);
}
}
httpRequest.body = requestForm;
httpRequest.formData = undefined;
const contentType = httpRequest.headers.get("Content-Type");
if (contentType && contentType.indexOf("multipart/form-data") !== -1) {
if (typeof requestForm.getBoundary === "function") {
httpRequest.headers.set(
"Content-Type",
`multipart/form-data; boundary=${requestForm.getBoundary()}`
);
} else {
// browser will automatically apply a suitable content-type header
httpRequest.headers.remove("Content-Type");
}
}
}
let body = httpRequest.body
? typeof httpRequest.body === "function"
? httpRequest.body()
: httpRequest.body
: undefined;
if (httpRequest.onUploadProgress && httpRequest.body) {
let loadedBytes = 0;
const uploadReportStream = new Transform({
transform: (chunk: string | Buffer, _encoding, callback) => {
loadedBytes += chunk.length;
httpRequest.onUploadProgress!({ loadedBytes });
callback(undefined, chunk);
},
});
if (isReadableStream(body)) {
body.pipe(uploadReportStream);
} else {
uploadReportStream.end(body);
}
body = uploadReportStream;
}
const platformSpecificRequestInit: Partial<RequestInit> = await this.prepareRequest(
httpRequest
);
const requestInit: RequestInit = {
body: body,
headers: httpRequest.headers.rawHeaders(),
method: httpRequest.method,
signal: abortController.signal,
redirect: "manual",
...platformSpecificRequestInit,
};
let operationResponse: HttpOperationResponse | undefined;
try {
const response: CommonResponse = await this.fetch(httpRequest.url, requestInit);
const headers = parseHeaders(response.headers);
operationResponse = {
headers: headers,
request: httpRequest,
status: response.status,
readableStreamBody: httpRequest.streamResponseBody
? ((response.body as unknown) as NodeJS.ReadableStream)
: undefined,
bodyAsText: !httpRequest.streamResponseBody ? await response.text() : undefined,
redirected: response.redirected,
url: response.url,
};
const onDownloadProgress = httpRequest.onDownloadProgress;
if (onDownloadProgress) {
const responseBody: ReadableStream<Uint8Array> | undefined = response.body || undefined;
if (isReadableStream(responseBody)) {
let loadedBytes = 0;
const downloadReportStream = new Transform({
transform: (chunk: string | Buffer, _encoding, callback) => {
loadedBytes += chunk.length;
onDownloadProgress({ loadedBytes });
callback(undefined, chunk);
},
});
responseBody.pipe(downloadReportStream);
operationResponse.readableStreamBody = downloadReportStream;
} else {
const length = parseInt(headers.get("Content-Length")!) || undefined;
if (length) {
// Calling callback for non-stream response for consistency with browser
onDownloadProgress({ loadedBytes: length });
}
}
}
await this.processRequest(operationResponse);
return operationResponse;
} catch (error) {
const fetchError: FetchError = error;
if (fetchError.code === "ENOTFOUND") {
throw new RestError(
fetchError.message,
RestError.REQUEST_SEND_ERROR,
undefined,
httpRequest
);
} else if (fetchError.type === "aborted") {
throw new RestError(
"The request was aborted",
RestError.REQUEST_ABORTED_ERROR,
undefined,
httpRequest
);
}
throw fetchError;
} finally {
// clean up event listener
if (httpRequest.abortSignal && abortListener) {
let uploadStreamDone = Promise.resolve();
if (isReadableStream(body)) {
uploadStreamDone = isStreamComplete(body);
}
let downloadStreamDone = Promise.resolve();
if (isReadableStream(operationResponse?.readableStreamBody)) {
downloadStreamDone = isStreamComplete(operationResponse!.readableStreamBody);
}
Promise.all([uploadStreamDone, downloadStreamDone])
.then(() => {
httpRequest.abortSignal?.removeEventListener("abort", abortListener!);
return;
})
.catch((_e) => {});
}
}
}
abstract async prepareRequest(httpRequest: WebResourceLike): Promise<Partial<RequestInit>>;
abstract async processRequest(operationResponse: HttpOperationResponse): Promise<void>;
abstract async fetch(input: CommonRequestInfo, init?: CommonRequestInit): Promise<CommonResponse>;
}
function isReadableStream(body: any): body is Readable {
return body && typeof body.pipe === "function";
}
function isStreamComplete(stream: Readable): Promise<void> {
return new Promise((resolve) => {
stream.on("close", resolve);
stream.on("end", resolve);
stream.on("error", resolve);
});
}
export function parseHeaders(headers: Headers): HttpHeadersLike {
const httpHeaders = new HttpHeaders();
headers.forEach((value, key) => {
httpHeaders.set(key, value);
});
return httpHeaders;
}