UNPKG

2.02 kBPlain TextView Raw
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License. See License.txt in the project root for license information.
3
4import * as http from "http";
5import * as https from "https";
6import node_fetch from "node-fetch";
7
8import {
9 CommonRequestInfo,
10 CommonRequestInit,
11 CommonResponse,
12 FetchHttpClient,
13} from "./fetchHttpClient";
14import { HttpOperationResponse } from "./httpOperationResponse";
15import { WebResourceLike } from "./webResource";
16import { createProxyAgent, ProxyAgent } from "./proxyAgent";
17
18export 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 /* no_op */
59 return;
60 }
61}