index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict'
  2. const { LRUCache } = require('lru-cache')
  3. const { normalizeOptions, cacheOptions } = require('./options')
  4. const { getProxy, proxyCache } = require('./proxy.js')
  5. const dns = require('./dns.js')
  6. const Agent = require('./agents.js')
  7. const agentCache = new LRUCache({ max: 20 })
  8. const getAgent = (url, { agent, proxy, noProxy, ...options } = {}) => {
  9. // false has meaning so this can't be a simple truthiness check
  10. if (agent != null) {
  11. return agent
  12. }
  13. url = new URL(url)
  14. const proxyForUrl = getProxy(url, { proxy, noProxy })
  15. const normalizedOptions = {
  16. ...normalizeOptions(options),
  17. proxy: proxyForUrl,
  18. }
  19. const cacheKey = cacheOptions({
  20. ...normalizedOptions,
  21. secureEndpoint: url.protocol === 'https:',
  22. })
  23. if (agentCache.has(cacheKey)) {
  24. return agentCache.get(cacheKey)
  25. }
  26. const newAgent = new Agent(normalizedOptions)
  27. agentCache.set(cacheKey, newAgent)
  28. return newAgent
  29. }
  30. module.exports = {
  31. getAgent,
  32. Agent,
  33. // these are exported for backwards compatability
  34. HttpAgent: Agent,
  35. HttpsAgent: Agent,
  36. cache: {
  37. proxy: proxyCache,
  38. agent: agentCache,
  39. dns: dns.cache,
  40. clear: () => {
  41. proxyCache.clear()
  42. agentCache.clear()
  43. dns.cache.clear()
  44. },
  45. },
  46. }