-
Notifications
You must be signed in to change notification settings - Fork 3
/
http_client.js
226 lines (182 loc) · 5.79 KB
/
http_client.js
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
// Copyright Titanium I.T. LLC.
import * as ensure from "util/ensure.js";
import http from "node:http";
import EventEmitter from "node:events";
import { OutputListener } from "util/output_listener.js";
import { ConfigurableResponses } from "util/configurable_responses.js";
const DEFAULT_NULLED_RESPONSE = {
status: 503,
headers: { NulledHttpClient: "default header" },
body: "Nulled HttpClient default body",
hang: false,
};
/** A general-purpose HTTP client. */
export class HttpClient {
/**
* Factory method. Creates the client.
* @returns {HttpClient} the client
*/
static create() {
ensure.signature(arguments, []);
return new HttpClient(http);
}
/**
* Factory method. Creates a 'nulled' client that simulates HTTP requests rather than making real requests.
* @param [responses] An object that contains the simulated responses each endpoint should return. Each
* endpoint gets a property. The property name contains the path (e.g., '/') and the property value
* contains the simulated response. If a response isn't provided, a default 501 (not implemented) or
* 503 (service unavailable) response is returned.
* @param [responses.status] the status code to return
* @param [responses.headers] the headers to return
* @param [responses.body] the body to return
* @param [responses.hang] if true, the request never returns
* @returns {HttpClient} the nulled client
*/
static createNull(responses) {
// signature checking in StubbedHttp
return new HttpClient(new StubbedHttp(responses));
}
/** Only for use by tests. (Use a factory method instead.) */
constructor(http) {
ensure.signature(arguments, [ Object ]);
this._http = http;
this._listener = new OutputListener();
}
/**
* Track the HTTP requests that are made.
* @returns {OutputTracker} the request tracker
*/
trackRequests() {
ensure.signature(arguments, []);
return this._listener.trackOutput();
}
/**
* Make the HTTP request. Returns a promise for the response and a function for cancelling the request.
* The response is an object containing { status, headers, body }.
* @param host the host to call
* @param port the port to use
* @param method the request method
* @param path the request path (URL)
* @param [headers] the request headers
* @param [body] the request body
* @returns {{responsePromise: Promise, cancelFn: () => void}} the response promise and cancellation function */
request({ host, port, method, path, headers = {}, body = "" }) {
ensure.signature(arguments, [{
host: String,
port: Number,
method: String,
path: String,
headers: [ undefined, Object ],
body: [ undefined, String ],
}]);
const requestOptions = {
host,
port,
method: method.toLowerCase(),
path,
headers: normalizeHeaders(headers),
body
};
if (requestOptions.method === "get" && requestOptions.body !== "") {
throw new Error("Don't include body with GET requests; Node won't send it");
}
const requestStatus = { inProgress: true };
const request = this.#sendRequest(requestOptions);
const cancelFn = this.#createCancelFn(request, requestStatus, requestOptions);
const responsePromise = new Promise((resolve, reject) => {
this.#handleResponse(request, requestStatus, resolve);
this.#handleError(request, reject);
});
return { responsePromise, cancelFn };
}
#sendRequest(requestOptions) {
const { body, ...httpOptions } = requestOptions;
const request = this._http.request(httpOptions);
request.end(body);
this._listener.emit(requestOptions);
return request;
}
#createCancelFn(request, requestStatus, requestOptions) {
return (message) => {
if (!requestStatus.inProgress) return false;
request.destroy(new Error(message));
this._listener.emit({ ...requestOptions, cancelled: true });
requestStatus.inProgress = false;
return true;
};
}
#handleResponse(request, requestStatus, resolve) {
request.once("response", (response) => {
const headers = { ...response.headers };
let body = "";
response.on("data", (chunk) => {
body += chunk;
});
response.on("end", () => {
requestStatus.inProgress = false;
resolve({
status: response.statusCode,
headers,
body,
});
});
});
}
#handleError(request, reject) {
request.once("error", reject);
}
}
function normalizeHeaders(headers) {
const normalized = Object.entries(headers).map(([ key, value ]) => [ key.toLowerCase(), value ]);
return Object.fromEntries(normalized);
}
class StubbedHttp {
constructor(responses = {}) {
ensure.signature(responses, [ [ undefined, Object ] ]);
this._responses = ConfigurableResponses.mapObject(responses, "nulled HTTP client");
}
request({ path }) {
return new StubbedRequest(path, this._responses[path]);
}
}
class StubbedRequest extends EventEmitter {
constructor(path, endpointResponses = ConfigurableResponses.create(DEFAULT_NULLED_RESPONSE)) {
super();
ensure.signature(arguments, [ String, [ undefined, Object, Array ]], [ "endpointResponses" ]);
this._endpointResponses = endpointResponses;
}
end() {
const response = this._endpointResponses.next();
setImmediate(() => {
this.emit("response", new StubbedResponse(response));
});
}
destroy(error) {
setImmediate(() => {
this.emit("error", error);
});
}
}
class StubbedResponse extends EventEmitter {
constructor({ status = 501, headers = {}, body = "", hang = false }) {
super();
ensure.signature(arguments, [{
status: [ undefined, Number ],
headers: [ undefined, Object ],
body: [ undefined, String ],
hang: [ undefined, Boolean ],
}], [ "response" ]);
this._status = status;
this._headers = normalizeHeaders(headers);
setImmediate(() => {
this.emit("data", body);
if (!hang) this.emit("end");
});
}
get statusCode() {
return this._status;
}
get headers() {
return this._headers;
}
}