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