-
-
Save ktpm489/a4d1ea0dfa574e1b80ce9fde1643d7de to your computer and use it in GitHub Desktop.
Cache service wrapper for node-cache module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import NodeCache from 'node-cache'; | |
class Cache { | |
constructor(ttlSeconds) { | |
this.cache = new NodeCache({ stdTTL: ttlSeconds, checkperiod: ttlSeconds * 0.2, useClones: false }); | |
} | |
get(key, storeFunction) { | |
const value = this.cache.get(key); | |
if (value) { | |
return Promise.resolve(value); | |
} | |
return storeFunction().then((result) => { | |
this.cache.set(key, result); | |
return result; | |
}); | |
} | |
del(keys) { | |
this.cache.del(keys); | |
} | |
delStartWith(startStr = '') { | |
if (!startStr) { | |
return; | |
} | |
const keys = this.cache.keys(); | |
for (const key of keys) { | |
if (key.indexOf(startStr) === 0) { | |
this.del(key); | |
} | |
} | |
} | |
flush() { | |
this.cache.flushAll(); | |
} | |
} | |
export default Cache; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment