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