Created
February 25, 2019 07:20
-
-
Save p1ho/1c7d81db13be872440699202fef1c474 to your computer and use it in GitHub Desktop.
Cache that implements expiration on top of flat-cache
This file contains hidden or 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
'use strict' | |
const flatCache = require('flat-cache') | |
module.exports = class Cache { | |
constructor (name, path, cacheTime = 0) { | |
this.name = name | |
this.path = path | |
this.cache = flatCache.load(name, path) | |
this.expire = cacheTime === 0 ? false : cacheTime * 1000 * 60 | |
} | |
getKey (key) { | |
var now = new Date().getTime() | |
var value = this.cache.getKey(key) | |
if (value === undefined || (value.expire !== false && value.expire < now)) { | |
return undefined | |
} else { | |
return value.data | |
} | |
} | |
setKey (key, value) { | |
var now = new Date().getTime() | |
this.cache.setKey(key, { | |
expire: this.expire === false ? false : now + this.expire, | |
data: value | |
}) | |
} | |
removeKey (key) { | |
this.cache.removeKey(key) | |
} | |
save () { | |
this.cache.save(true) | |
} | |
remove () { | |
flatCache.clearCacheById(this.name, this.path) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the suggestion, is this what you mean?