-
Notifications
You must be signed in to change notification settings - Fork 74
/
fetch-http-handler.ts
184 lines (161 loc) · 5.96 KB
/
fetch-http-handler.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
import { HttpHandler, HttpRequest, HttpResponse } from "@smithy/protocol-http";
import { buildQueryString } from "@smithy/querystring-builder";
import type { FetchHttpHandlerOptions } from "@smithy/types";
import { HeaderBag, HttpHandlerOptions, Provider } from "@smithy/types";
import { requestTimeout } from "./request-timeout";
declare let AbortController: any;
export { FetchHttpHandlerOptions };
type FetchHttpHandlerConfig = FetchHttpHandlerOptions;
/**
* @internal
* Detection of keepalive support. Can be overridden for testing.
*/
export const keepAliveSupport = {
supported: Boolean(typeof Request !== "undefined" && "keepalive" in new Request("https://[::1]")),
};
/**
* @internal
*/
type AdditionalRequestParameters = {
// This is required in Node.js when Request has a body, and does nothing in the browser.
// Duplex: half means the request is fully transmitted before attempting to process the response.
// As of writing this is the only accepted value in https://fetch.spec.whatwg.org/.
duplex?: "half";
};
/**
* @public
*
* HttpHandler implementation using browsers' `fetch` global function.
*/
export class FetchHttpHandler implements HttpHandler<FetchHttpHandlerConfig> {
private config?: FetchHttpHandlerConfig;
private configProvider: Promise<FetchHttpHandlerConfig>;
/**
* @returns the input if it is an HttpHandler of any class,
* or instantiates a new instance of this handler.
*/
public static create(
instanceOrOptions?: HttpHandler<any> | FetchHttpHandlerOptions | Provider<FetchHttpHandlerOptions | void>
) {
if (typeof (instanceOrOptions as any)?.handle === "function") {
// is already an instance of HttpHandler.
return instanceOrOptions as HttpHandler<any>;
}
// input is ctor options or undefined.
return new FetchHttpHandler(instanceOrOptions as FetchHttpHandlerConfig);
}
constructor(options?: FetchHttpHandlerOptions | Provider<FetchHttpHandlerOptions | void>) {
if (typeof options === "function") {
this.configProvider = options().then((opts) => opts || {});
} else {
this.config = options ?? {};
this.configProvider = Promise.resolve(this.config);
}
}
destroy(): void {
// Do nothing. TLS and HTTP/2 connection pooling is handled by the browser.
}
async handle(request: HttpRequest, { abortSignal }: HttpHandlerOptions = {}): Promise<{ response: HttpResponse }> {
if (!this.config) {
this.config = await this.configProvider;
}
const requestTimeoutInMs = this.config!.requestTimeout;
const keepAlive = this.config!.keepAlive === true;
// if the request was already aborted, prevent doing extra work
if (abortSignal?.aborted) {
const abortError = new Error("Request aborted");
abortError.name = "AbortError";
return Promise.reject(abortError);
}
let path = request.path;
const queryString = buildQueryString(request.query || {});
if (queryString) {
path += `?${queryString}`;
}
if (request.fragment) {
path += `#${request.fragment}`;
}
let auth = "";
if (request.username != null || request.password != null) {
const username = request.username ?? "";
const password = request.password ?? "";
auth = `${username}:${password}@`;
}
const { port, method } = request;
const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`;
// Request constructor doesn't allow GET/HEAD request with body
// ref: https://github.com/whatwg/fetch/issues/551
const body = method === "GET" || method === "HEAD" ? undefined : request.body;
const requestOptions: RequestInit & AdditionalRequestParameters = {
body,
headers: new Headers(request.headers),
method: method,
};
if (body) {
requestOptions.duplex = "half";
}
// some browsers support abort signal
if (typeof AbortController !== "undefined") {
requestOptions.signal = abortSignal as AbortSignal;
}
// some browsers support keepalive
if (keepAliveSupport.supported) {
requestOptions.keepalive = keepAlive;
}
const fetchRequest = new Request(url, requestOptions);
const raceOfPromises = [
fetch(fetchRequest).then((response) => {
const fetchHeaders: any = response.headers;
const transformedHeaders: HeaderBag = {};
for (const pair of <Array<string[]>>fetchHeaders.entries()) {
transformedHeaders[pair[0]] = pair[1];
}
// Check for undefined as well as null.
const hasReadableStream = response.body != undefined;
// Return the response with buffered body
if (!hasReadableStream) {
return response.blob().then((body) => ({
response: new HttpResponse({
headers: transformedHeaders,
reason: response.statusText,
statusCode: response.status,
body,
}),
}));
}
// Return the response with streaming body
return {
response: new HttpResponse({
headers: transformedHeaders,
reason: response.statusText,
statusCode: response.status,
body: response.body,
}),
};
}),
requestTimeout(requestTimeoutInMs),
];
if (abortSignal) {
raceOfPromises.push(
new Promise<never>((resolve, reject) => {
abortSignal.onabort = () => {
const abortError = new Error("Request aborted");
abortError.name = "AbortError";
reject(abortError);
};
})
);
}
return Promise.race(raceOfPromises);
}
updateHttpClientConfig(key: keyof FetchHttpHandlerConfig, value: FetchHttpHandlerConfig[typeof key]): void {
this.config = undefined;
this.configProvider = this.configProvider.then((config) => {
(config as Record<typeof key, typeof value>)[key] = value;
return config;
});
}
httpHandlerConfigs(): FetchHttpHandlerConfig {
return this.config ?? {};
}
}