diff --git a/source/index.js b/source/index.js index 52a86f2..55dd1f3 100644 --- a/source/index.js +++ b/source/index.js @@ -97,6 +97,10 @@ class CacheableLookup { this._cache = cache; this._resolver = resolver; this._dnsLookup = lookup && promisify(lookup); + this.stats = { + cache: 0, + query: 0 + }; if (this._resolver instanceof AsyncResolver) { this._resolve4 = this._resolver.resolve4.bind(this._resolver); @@ -214,16 +218,20 @@ class CacheableLookup { let source = 'cache'; let cached = await this._cache.get(hostname); + if (cached) { + this.stats.cache++; + } + if (!cached) { const pending = this._pending[hostname]; - if (pending) { + this.stats.cache++; cached = await pending; } else { source = 'query'; const newPromise = this.queryAndCache(hostname); this._pending[hostname] = newPromise; - + this.stats.query++; try { cached = await newPromise; } finally { diff --git a/tests/test.js b/tests/test.js index 472bbf5..8daee25 100644 --- a/tests/test.js +++ b/tests/test.js @@ -1067,3 +1067,27 @@ test.cb.failing('throws original lookup error if not recognized', t => { t.end(); }); }); + +test('cache and query stats', async t => { + const cacheable = new CacheableLookup({resolver}); + + t.is(cacheable.stats.query, 0); + t.is(cacheable.stats.cache, 0); + + let entries = await cacheable.lookupAsync('temporary', {all: true, family: 4}); + verify(t, entries, [ + {address: '127.0.0.1', family: 4, source: 'query'} + ]); + + t.is(cacheable.stats.query, 1); + t.is(cacheable.stats.cache, 0); + + entries = await cacheable.lookupAsync('temporary', {all: true, family: 4}); + + verify(t, entries, [ + {address: '127.0.0.1', family: 4, source: 'cache'} + ]); + + t.is(cacheable.stats.query, 1); + t.is(cacheable.stats.cache, 1); +});