UNPKG

1.35 kBJavaScriptView Raw
1module.exports = getRequestAgent
2
3const urlParse = require('url').parse
4
5const HttpAgent = require('http').Agent
6const HttpsAgent = require('https').Agent
7const HttpProxyAgent = require('http-proxy-agent')
8const HttpsProxyAgent = require('https-proxy-agent')
9const merge = require('lodash/merge')
10const omit = require('lodash/omit')
11const pick = require('lodash/pick')
12
13const deprecate = require('./deprecate')
14
15function 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 /* istanbul ignore if */
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 /* istanbul ignore if */
48 if (protocol === 'http') {
49 return new HttpAgent(agentOptions)
50 }
51
52 return new HttpsAgent(agentOptions)
53}