You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dns.js 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const LRUCache = require('lru-cache')
  2. const dns = require('dns')
  3. const defaultOptions = exports.defaultOptions = {
  4. family: undefined,
  5. hints: dns.ADDRCONFIG,
  6. all: false,
  7. verbatim: undefined,
  8. }
  9. const lookupCache = exports.lookupCache = new LRUCache({ max: 50 })
  10. // this is a factory so that each request can have its own opts (i.e. ttl)
  11. // while still sharing the cache across all requests
  12. exports.getLookup = (dnsOptions) => {
  13. return (hostname, options, callback) => {
  14. if (typeof options === 'function') {
  15. callback = options
  16. options = null
  17. } else if (typeof options === 'number') {
  18. options = { family: options }
  19. }
  20. options = { ...defaultOptions, ...options }
  21. const key = JSON.stringify({
  22. hostname,
  23. family: options.family,
  24. hints: options.hints,
  25. all: options.all,
  26. verbatim: options.verbatim,
  27. })
  28. if (lookupCache.has(key)) {
  29. const [address, family] = lookupCache.get(key)
  30. process.nextTick(callback, null, address, family)
  31. return
  32. }
  33. dnsOptions.lookup(hostname, options, (err, address, family) => {
  34. if (err) {
  35. return callback(err)
  36. }
  37. lookupCache.set(key, [address, family], { ttl: dnsOptions.ttl })
  38. return callback(null, address, family)
  39. })
  40. }
  41. }