-
Notifications
You must be signed in to change notification settings - Fork 91
/
fetch-http-handler.ts
169 lines (147 loc) · 5.24 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
import { HttpHandler, HttpRequest, HttpResponse } from "@smithy/protocol-http";
import { buildQueryString } from "@smithy/querystring-builder";
import { HeaderBag, HttpHandlerOptions, Provider } from "@smithy/types";
import { requestTimeout } from "./request-timeout";
declare let AbortController: any;
/**
* Represents the http options that can be passed to a browser http client.
*/
export interface FetchHttpHandlerOptions {
/**
* The number of milliseconds a request can take before being automatically
* terminated.
*/
requestTimeout?: number;
/**
* Whether to allow the request to outlive the page. Default value is true
*/
keepAlive?: boolean;
}
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("")),
};
/**
* @public
*
* HttpHandler implementation using browsers' `fetch` global function.
*/
export class FetchHttpHandler implements HttpHandler<FetchHttpHandlerConfig> {
private config?: FetchHttpHandlerConfig;
private configProvider: Promise<FetchHttpHandlerConfig>;
constructor(options?: FetchHttpHandlerOptions | Provider<FetchHttpHandlerOptions | undefined>) {
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 = {
body,
headers: new Headers(request.headers),
method: method,
};
// some browsers support abort signal
if (typeof AbortController !== "undefined") {
(requestOptions as any)["signal"] = abortSignal;
}
// some browsers support keepalive
if (keepAliveSupport.supported) {
(requestOptions as any)["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 ?? {};
}
}