async-cache-dedupe
Advanced tools
Comparing version 1.3.0 to 1.4.0
{ | ||
"name": "async-cache-dedupe", | ||
"version": "1.3.0", | ||
"version": "1.4.0", | ||
"description": "An async deduping cache", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -22,3 +22,3 @@ 'use strict' | ||
if (options.ttl && (typeof options.ttl !== 'number' || options.ttl < 0)) { | ||
if (options.ttl && (typeof options.ttl !== 'number' || options.ttl < 0 || !Number.isInteger(options.ttl))) { | ||
throw new Error('ttl must be a positive integer greater than 0') | ||
@@ -96,2 +96,6 @@ } | ||
if (opts.ttl && (typeof opts.ttl !== 'number' || opts.ttl < 0 || !Number.isInteger(opts.ttl))) { | ||
throw new Error('ttl must be a positive integer greater than 0') | ||
} | ||
let storage | ||
@@ -236,12 +240,14 @@ if (opts.storage) { | ||
const storageKey = this.getStorageKey(key) | ||
let data = this.storage.get(storageKey) | ||
if (data && typeof data.then === 'function') { data = await data } | ||
if (this.ttl > 0) { | ||
let data = this.storage.get(storageKey) | ||
if (data && typeof data.then === 'function') { data = await data } | ||
if (data !== undefined) { | ||
this.onHit(key) | ||
return data | ||
if (data !== undefined) { | ||
this.onHit(key) | ||
return data | ||
} | ||
this.onMiss(key) | ||
} | ||
this.onMiss(key) | ||
const result = await this.func(args, key) | ||
@@ -248,0 +254,0 @@ |
@@ -6,3 +6,3 @@ 'use strict' | ||
const createStorage = require('../src/storage') | ||
const { kStorages } = require('../src/symbol') | ||
const { kStorage, kStorages } = require('../src/symbol') | ||
@@ -55,2 +55,20 @@ const { test } = t | ||
}) | ||
test('should bypass storage when ttl is 0', async (t) => { | ||
t.plan(1) | ||
const cache = new Cache({ storage: createStorage() }) | ||
cache[kStorage].get = () => { | ||
t.fail('should bypass storage') | ||
} | ||
cache[kStorage].set = () => { | ||
t.fail('should bypass storage') | ||
} | ||
cache.define('f', { ttl: 0 }, async (k) => { | ||
t.equal(k, 'foo') | ||
return { k } | ||
}) | ||
await cache.f('foo') | ||
}) | ||
}) | ||
@@ -57,0 +75,0 @@ |
@@ -35,2 +35,24 @@ 'use strict' | ||
test('global ttl is a positive integer', async (t) => { | ||
t.plan(1) | ||
try { | ||
// eslint-disable-next-line no-new | ||
new Cache({ ttl: 3.14, storage: createStorage() }) | ||
} catch (err) { | ||
t.equal(err.message, 'ttl must be a positive integer greater than 0') | ||
} | ||
}) | ||
test('function ttl is a positive integer', async (t) => { | ||
t.plan(1) | ||
const cache = new Cache({ storage: createStorage() }) | ||
try { | ||
cache.define('fetchSomething', { ttl: 3.14 }, async (k) => ({ k })) | ||
} catch (err) { | ||
t.equal(err.message, 'ttl must be a positive integer greater than 0') | ||
} | ||
}) | ||
test('ttl expires', async (t) => { | ||
@@ -37,0 +59,0 @@ t.plan(5) |
144373
3503