1 |
|
2 |
|
3 |
|
4 | import * as http from "http";
|
5 | import * as https from "https";
|
6 | import node_fetch from "node-fetch";
|
7 |
|
8 | import {
|
9 | CommonRequestInfo,
|
10 | CommonRequestInit,
|
11 | CommonResponse,
|
12 | FetchHttpClient,
|
13 | } from "./fetchHttpClient";
|
14 | import { HttpOperationResponse } from "./httpOperationResponse";
|
15 | import { WebResourceLike } from "./webResource";
|
16 | import { createProxyAgent, ProxyAgent } from "./proxyAgent";
|
17 |
|
18 | export class NodeFetchHttpClient extends FetchHttpClient {
|
19 | async fetch(input: CommonRequestInfo, init?: CommonRequestInit): Promise<CommonResponse> {
|
20 | return (node_fetch(input, init) as unknown) as Promise<CommonResponse>;
|
21 | }
|
22 |
|
23 | async prepareRequest(httpRequest: WebResourceLike): Promise<Partial<RequestInit>> {
|
24 | const requestInit: Partial<RequestInit & { agent?: any }> = {};
|
25 |
|
26 | if (httpRequest.agentSettings) {
|
27 | const { http: httpAgent, https: httpsAgent } = httpRequest.agentSettings;
|
28 | if (httpsAgent && httpRequest.url.startsWith("https")) {
|
29 | requestInit.agent = httpsAgent;
|
30 | } else if (httpAgent) {
|
31 | requestInit.agent = httpAgent;
|
32 | }
|
33 | } else if (httpRequest.proxySettings) {
|
34 | const tunnel: ProxyAgent = createProxyAgent(
|
35 | httpRequest.url,
|
36 | httpRequest.proxySettings,
|
37 | httpRequest.headers
|
38 | );
|
39 | requestInit.agent = tunnel.agent;
|
40 | }
|
41 |
|
42 | if (httpRequest.keepAlive === true) {
|
43 | if (requestInit.agent) {
|
44 | requestInit.agent.keepAlive = true;
|
45 | } else {
|
46 | const options: http.AgentOptions | https.AgentOptions = { keepAlive: true };
|
47 | const agent = httpRequest.url.startsWith("https")
|
48 | ? new https.Agent(options)
|
49 | : new http.Agent(options);
|
50 | requestInit.agent = agent;
|
51 | }
|
52 | }
|
53 |
|
54 | return requestInit;
|
55 | }
|
56 |
|
57 | async processRequest(_operationResponse: HttpOperationResponse): Promise<void> {
|
58 |
|
59 | return;
|
60 | }
|
61 | }
|