dns.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict'
  2. const { LRUCache } = require('lru-cache')
  3. const dns = require('dns')
  4. // this is a factory so that each request can have its own opts (i.e. ttl)
  5. // while still sharing the cache across all requests
  6. const cache = new LRUCache({ max: 50 })
  7. const getOptions = ({
  8. family = 0,
  9. hints = dns.ADDRCONFIG,
  10. all = false,
  11. verbatim = undefined,
  12. ttl = 5 * 60 * 1000,
  13. lookup = dns.lookup,
  14. }) => ({
  15. // hints and lookup are returned since both are top level properties to (net|tls).connect
  16. hints,
  17. lookup: (hostname, ...args) => {
  18. const callback = args.pop() // callback is always last arg
  19. const lookupOptions = args[0] ?? {}
  20. const options = {
  21. family,
  22. hints,
  23. all,
  24. verbatim,
  25. ...(typeof lookupOptions === 'number' ? { family: lookupOptions } : lookupOptions),
  26. }
  27. const key = JSON.stringify({ hostname, ...options })
  28. if (cache.has(key)) {
  29. const cached = cache.get(key)
  30. return process.nextTick(callback, null, ...cached)
  31. }
  32. lookup(hostname, options, (err, ...result) => {
  33. if (err) {
  34. return callback(err)
  35. }
  36. cache.set(key, result, { ttl })
  37. return callback(null, ...result)
  38. })
  39. },
  40. })
  41. module.exports = {
  42. cache,
  43. getOptions,
  44. }