Skip to content

Commit

Permalink
Tidy up code a bit
Browse files Browse the repository at this point in the history
Signed-off-by: Levko Kravets <levko.ne@gmail.com>
  • Loading branch information
kravets-levko committed Oct 4, 2023
1 parent f25616a commit ad01894
Showing 1 changed file with 42 additions and 30 deletions.
72 changes: 42 additions & 30 deletions lib/connection/connections/HttpConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,43 +38,55 @@ export default class HttpConnection implements IConnectionProvider {

public async getAgent(): Promise<http.Agent> {
if (!this.agent) {
const { options } = this;

const httpAgentOptions: http.AgentOptions = {
keepAlive: true,
maxSockets: 5,
keepAliveMsecs: 10000,
timeout: options.socketTimeout ?? globalConfig.socketTimeout,
};

const httpsAgentOptions: https.AgentOptions = {
...httpAgentOptions,
minVersion: 'TLSv1.2',
rejectUnauthorized: false,
ca: options.ca,
cert: options.cert,
key: options.key,
};

if (options.proxy !== undefined) {
const proxyUrl = buildProxyUrl(options.proxy);
const proxyProtocol = `${options.proxy.protocol}:`;

this.agent = new ProxyAgent({
...httpAgentOptions,
getProxyForUrl: () => proxyUrl,
httpsAgent: new https.Agent(httpsAgentOptions),
httpAgent: new http.Agent(httpAgentOptions),
protocol: proxyProtocol,
});
if (this.options.proxy !== undefined) {
this.agent = this.createProxyAgent(this.options.proxy);
} else {
this.agent = options.https ? new https.Agent(httpsAgentOptions) : new http.Agent(httpAgentOptions);
this.agent = this.options.https ? this.createHttpsAgent() : this.createHttpAgent();
}
}

return this.agent;
}

private getAgentDefaultOptions(): http.AgentOptions {
return {
keepAlive: true,
maxSockets: 5,
keepAliveMsecs: 10000,
timeout: this.options.socketTimeout ?? globalConfig.socketTimeout,
};
}

private createHttpAgent(): http.Agent {
const httpAgentOptions = this.getAgentDefaultOptions();
return new http.Agent(httpAgentOptions);
}

private createHttpsAgent(): https.Agent {
const httpsAgentOptions: https.AgentOptions = {
...this.getAgentDefaultOptions(),
minVersion: 'TLSv1.2',
rejectUnauthorized: false,
ca: this.options.ca,
cert: this.options.cert,
key: this.options.key,
};
return new https.Agent(httpsAgentOptions);
}

private createProxyAgent(proxyOptions: ProxyOptions): ProxyAgent {
const proxyUrl = buildProxyUrl(proxyOptions);
const proxyProtocol = `${proxyOptions.protocol}:`;

return new ProxyAgent({
...this.getAgentDefaultOptions(),
getProxyForUrl: () => proxyUrl,
httpsAgent: this.createHttpsAgent(),
httpAgent: this.createHttpAgent(),
protocol: proxyProtocol,
});
}

public async getThriftConnection(): Promise<any> {
if (!this.connection) {
const { options } = this;
Expand Down

0 comments on commit ad01894

Please sign in to comment.