@appigram/keyv-lru
Version:
An in-memory LRU back-end for Keyv.
78 lines (61 loc) • 1.78 kB
JavaScript
;
const lru = require('tiny-lru');
const KeyvLru = require('./KeyvLru');
/**
* An adaptor from tiny-lru to a Map API.
*
* This version uses a managed TTL strategy instead of tiny-lru. This is useful
* for serverless architectures. tiny-lru expires entries based on timers, that
* means that the event loop is not empty when the lambda function is finished.
* That blocks the end of the execution.
*
* This implementation will store the expiration time along with the cached data
* and it will deleter expired items upon retrieval. Alternatively there is an
* evictExpired method that will evict all the expired items.
*/
class KeyvLruManagedTtl extends KeyvLru {
constructor(options = {
max: 500
}) {
super(options);
this.cache = lru(options.max);
}
get(key) {
const item = this.cache.get(key);
if (!item) {
return undefined;
}
if (typeof item.expires === 'undefined') {
return item.data;
}
if (item.expires > Date.now()) {
// It's not expired yet.
return item.data;
} // Schedule removal and return undefined.
process.nextTick(() => this.delete(key));
return undefined;
}
set(key, value, ttl) {
const item = {
data: value
};
const theTtl = ttl || this.defaultTtl;
if (typeof theTtl !== 'undefined') {
item.expires = theTtl + Date.now();
}
this.cache.set(key, item);
return 1;
}
/**
* Loop through all the cache entries and get them.
*
* This has the effect to delete all the expired cache entries.
*
* @return {void}
*/
evictExpired() {
// Getting the entries will cause evition on expired entries.
this.cache.keys().forEach(this.get.bind(this));
}
}
module.exports = KeyvLruManagedTtl;