Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@p1ho
Created February 25, 2019 07:20
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save p1ho/1c7d81db13be872440699202fef1c474 to your computer and use it in GitHub Desktop.
Save p1ho/1c7d81db13be872440699202fef1c474 to your computer and use it in GitHub Desktop.
Cache that implements expiration on top of flat-cache
'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)
}
}
@tiagosiebler
Copy link

Why don't you make a npm module for this? It's a very helpful one.

@p1ho
Copy link
Author

p1ho commented Jul 2, 2019

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.

@AmrSaber
Copy link

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.

@p1ho
Copy link
Author

p1ho commented Jun 15, 2020

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