get-request-agent.js 1.3 KB

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