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 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) | |
} | |
} |
Sorry for the late reply (I must have missed the notification), thanks for commenting!
I think there are tons of caching libraries on npm already that do things the same way, so I did not bother.
But if it's helpful to people, maybe I can make a PR to the flat-cache library I used in this gist.
I want to suggest an update that you remove the expired data from the cache when you get and check them.
This will be useful especially that you use the noPrune
option on saving.
I want to suggest an update that you remove the expired data from the cache when you get and check them.
This will be useful especially that you use the
noPrune
option on saving.
Thanks for the suggestion, is this what you mean?
getKey (key) {
var now = new Date().getTime()
var value = this.cache.getKey(key)
if (value === undefined) {
return undefined
} else {
if (value.expire !== false && value.expire < now)) {
this.removeKey(key)
return undefined
} else {
return value.data
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why don't you make a npm module for this? It's a very helpful one.