-
Notifications
You must be signed in to change notification settings - Fork 57
/
httpURLConnectionClient.ts
210 lines (172 loc) · 8.79 KB
/
httpURLConnectionClient.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
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import { ClientRequest, IncomingHttpHeaders, IncomingMessage } from "http";
import { Agent, AgentOptions, request as httpsRequest } from "https";
import { HttpsProxyAgent } from "https-proxy-agent";
import * as fs from "fs";
import { URL, URLSearchParams } from "url";
import Client from "../client";
import Config from "../config";
import HttpClientException from "./httpClientException";
import checkServerIdentity from "../helpers/checkServerIdentity";
import { ApiError } from "../typings/apiError";
import ApiException from "../services/exception/apiException";
import ClientInterface from "./clientInterface";
import { ApiConstants } from "../constants/apiConstants";
import { IRequest } from "../typings/requestOptions";
class HttpURLConnectionClient implements ClientInterface {
private static CHARSET = "utf-8";
public proxy?: AgentOptions;
private agentOptions!: AgentOptions;
public request(
endpoint: string, json: string, config: Config, isApiRequired: boolean,
requestOptions: IRequest.Options,
): Promise<string | HttpClientException | ApiException> {
requestOptions.headers = {};
requestOptions.timeout = config.connectionTimeoutMillis;
if (config.certificatePath) {
this.installCertificateVerifier(config.certificatePath);
}
const apiKey = config.apiKey;
if (isApiRequired && !apiKey) {
return Promise.reject(new ApiException("Invalid X-API-Key was used", 401));
}
if (apiKey) {
requestOptions.headers[ApiConstants.API_KEY] = apiKey;
} else {
const authString = `${config.username}:${config.password}`;
const authStringEnc = Buffer.from(authString, "utf8").toString("base64");
requestOptions.headers.Authorization = `Basic ${authStringEnc}`;
}
requestOptions.headers[ApiConstants.CONTENT_TYPE] = ApiConstants.APPLICATION_JSON_TYPE;
const httpConnection: ClientRequest = this.createRequest(endpoint, requestOptions, config.applicationName);
return this.doPostRequest(httpConnection, json);
}
public post(endpoint: string, postParameters: [string, string][], config: Config): Promise<HttpClientException | string> {
const postQuery: string = this.getQuery(postParameters);
const connectionRequest: ClientRequest = this.createRequest(endpoint, {}, config.applicationName);
return this.doPostRequest(connectionRequest, postQuery);
}
private createRequest(endpoint: string, requestOptions: IRequest.Options, applicationName?: string): ClientRequest {
if (!requestOptions.headers) {
requestOptions.headers = {};
}
const url = new URL(endpoint);
requestOptions.hostname = url.hostname;
requestOptions.protocol = url.protocol;
requestOptions.port = url.port;
requestOptions.path = url.pathname;
if (requestOptions.params) {
requestOptions.path += '?' + new URLSearchParams(requestOptions.params).toString();
}
if (requestOptions && requestOptions.idempotencyKey) {
requestOptions.headers[ApiConstants.IDEMPOTENCY_KEY] = requestOptions.idempotencyKey;
delete requestOptions.idempotencyKey;
}
if (this.proxy && this.proxy.host) {
const { host, port, ...options } = this.proxy;
requestOptions.agent = new HttpsProxyAgent({ host, port: port || 443, ...options });
} else {
requestOptions.agent = new Agent(this.agentOptions);
}
requestOptions.headers["Cache-Control"] = "no-cache";
if (!requestOptions.method) {
requestOptions.method = ApiConstants.METHOD_POST;
}
requestOptions.headers[ApiConstants.ACCEPT_CHARSET] = HttpURLConnectionClient.CHARSET;
requestOptions.headers[ApiConstants.USER_AGENT] = `${applicationName} ${Client.LIB_NAME}/${Client.LIB_VERSION}`;
return httpsRequest(requestOptions);
}
private getQuery(params: [string, string][]): string {
return params.map(([key, value]): string => `${key}=${value}`).join("&");
}
private doPostRequest(connectionRequest: ClientRequest, json: string): Promise<HttpClientException | string> {
return new Promise((resolve, reject): void => {
connectionRequest.flushHeaders();
connectionRequest.on("response", (res: IncomingMessage): void => {
const response: { headers: IncomingHttpHeaders; body: string; statusCode: number | undefined } = {
statusCode: res.statusCode,
headers: res.headers,
body: ""
};
const getException = (responseBody: string): HttpClientException => new HttpClientException({
message: `HTTP Exception: ${response.statusCode}. ${res.statusMessage}`,
statusCode: response.statusCode,
errorCode: undefined,
responseHeaders: response.headers,
responseBody,
});
let exception: HttpClientException | Error = getException(response.body.toString());
res.on("data", (chunk: string): void => {
response.body += chunk;
});
res.on("end", (): void => {
if (!res.complete) {
reject(new Error("The connection was terminated while the message was still being sent"));
}
if (res.statusCode && (res.statusCode < 200 || res.statusCode >= 300)) {
try {
const formattedData: ApiError | {[key: string]: never} = JSON.parse(response.body);
const isApiError = "status" in formattedData;
const isRequestError = "errors" in formattedData;
if (isApiError) {
exception = new HttpClientException({
message: `HTTP Exception: ${formattedData.status}. ${res.statusMessage}: ${formattedData.message}`,
statusCode: formattedData.status,
errorCode: formattedData.errorCode,
responseHeaders: res.headers,
responseBody: response.body,
});
} else if (isRequestError) {
exception = new Error(response.body);
} else {
exception = getException(response.body);
}
} catch (e) {
reject(exception);
} finally {
reject(exception);
}
}
resolve(response.body as string);
});
res.on("error", reject);
});
connectionRequest.on("timeout", (): void => {
connectionRequest.abort();
});
connectionRequest.on("error", (e) => reject(new ApiException(e.message)));
connectionRequest.write(Buffer.from(json));
connectionRequest.end();
});
}
private installCertificateVerifier(terminalCertificatePath: string): void | Promise<HttpClientException> {
try {
const certificateInput = fs.readFileSync(terminalCertificatePath);
this.agentOptions = {
ca: certificateInput,
checkServerIdentity,
};
} catch (e) {
const message = e instanceof Error ? e.message: "undefined";
return Promise.reject(new HttpClientException({ message: `Error loading certificate from path: ${message}` }));
}
}
}
export default HttpURLConnectionClient;