1 | module.exports = getRequestAgent
|
2 |
|
3 | const urlParse = require('url').parse
|
4 |
|
5 | const HttpAgent = require('http').Agent
|
6 | const HttpsAgent = require('https').Agent
|
7 | const HttpProxyAgent = require('http-proxy-agent')
|
8 | const HttpsProxyAgent = require('https-proxy-agent')
|
9 | const merge = require('lodash/merge')
|
10 | const omit = require('lodash/omit')
|
11 | const pick = require('lodash/pick')
|
12 |
|
13 | const deprecate = require('./deprecate')
|
14 |
|
15 | function getRequestAgent (baseUrl, options) {
|
16 | if (options.agent) {
|
17 | return options.agent
|
18 | }
|
19 |
|
20 | const agentOptionNames = ['ca', 'proxy', 'rejectUnauthorized', 'family'].filter(key => key in options)
|
21 |
|
22 | if (agentOptionNames.length === 0) {
|
23 | return
|
24 | }
|
25 | agentOptionNames.forEach(option => {
|
26 | deprecate(`options.${option} (use "options.agent" instead)`)
|
27 | })
|
28 |
|
29 | const agentOptions = pick(options, agentOptionNames)
|
30 |
|
31 | const protocol = urlParse(baseUrl).protocol.replace(':', '')
|
32 |
|
33 |
|
34 | if ('proxy' in options) {
|
35 | const proxyAgentOptions = merge(
|
36 | urlParse(agentOptions.proxy),
|
37 | omit(agentOptions, 'proxy')
|
38 | )
|
39 |
|
40 | if (protocol === 'http') {
|
41 | return new HttpProxyAgent(proxyAgentOptions)
|
42 | }
|
43 |
|
44 | return new HttpsProxyAgent(proxyAgentOptions)
|
45 | }
|
46 |
|
47 |
|
48 | if (protocol === 'http') {
|
49 | return new HttpAgent(agentOptions)
|
50 | }
|
51 |
|
52 | return new HttpsAgent(agentOptions)
|
53 | }
|