Last active
February 14, 2016 23:06
-
-
Save alanrsoares/014e7ef6f70255b31de2 to your computer and use it in GitHub Desktop.
An overly-simplified cache library for node v4+
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 lowdb = require('lowdb'); | |
const storage = require('lowdb/file-sync'); | |
const db = lowdb(`${ __dirname }/db.json`, { storage }); | |
const COLLECTION_ID = 'cache'; | |
const ONE_HOUR = 3600; | |
const isValidCacheKey = (key, ttl) => | |
Math.floor((Date.now() - key.created) / 1000) <= ttl; | |
class CacheKey { | |
constructor(key, value) { | |
this.created = Date.now(); | |
Object.assign(this, { key, value }); | |
} | |
} | |
class Cache { | |
constructor(opts) { | |
this.stdTTL = opts.stdTTL || 600; | |
this.db = db(COLLECTION_ID); | |
} | |
get(key) { | |
const cached = this.db.find({ key }); | |
return cached && isValidCacheKey(cached, this.stdTTL) | |
? cached.value | |
: this.invalidate(key); | |
} | |
set(key, value) { | |
this.db.push(new CacheKey(key, value)); | |
} | |
invalidate(key) { | |
this.db.remove({ key }); | |
} | |
} | |
module.exports = new Cache({ stdTTL: ONE_HOUR }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment