Last active
January 30, 2018 19:27
-
-
Save okoghenun/dc176adc88024a914ffaf8d6c4c7e6b9 to your computer and use it in GitHub Desktop.
Redis style API wrapper around localforage as a cache mechanism
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 storage from 'localforage'; | |
/** | |
* Redis style API wrapper around localforage as a cache mechanism | |
*/ | |
export default class CacheClient { | |
constructor(config) { | |
defaultConfig = { | |
cacheDuration: 600, // 1o mins | |
}; | |
this.config = Object.assign({}, defaultConfig, config); | |
// By default mock out the storage interface | |
// TODO set up an inmemory store as a fallback | |
this.db = { | |
getItem: () => Promise.resolve(null), | |
setItem: () => Promise.resolve(null), | |
removeItem: () => Promise.resolve(null), | |
}; | |
storage.ready().then(() => { | |
this.db = storage; | |
}).catch((e) => { | |
console.error('[Cache Client] error could not set up database', e); // `No available storage method found.` | |
}); | |
} | |
/** | |
* Return an item from cache | |
* @param key | |
* @returns {Request|Promise.<TResult>|*} | |
*/ | |
get(key) { | |
return this.db.getItem(key) | |
.then((record) => { | |
if (record) { | |
if (!record.ts || (new Date()).getTime() < parseInt(record.ts, 10)) { | |
// If there is no expiry timestamp, or if the expiry time hasn't been reached yet | |
return record.value; | |
} | |
// If time has passed, remove the record from the cache | |
return this.db.removeItem(key); | |
} | |
return record; | |
}); | |
} | |
/** | |
* Adds an item to cache | |
* @param key | |
* @param value | |
* @param ttl | |
* @returns {*} | |
*/ | |
set(key, value, ttl) { | |
const cacheTTL = ttl || this.config.cacheDuration; | |
const record = { | |
value, | |
// Multiply ttl by 1000 to convert it to milliseconds | |
ts: (new Date()).getTime() + parseInt(cacheTTL * 1000, 10), | |
}; | |
return this.db.setItem(key, record); | |
} | |
/** | |
* Removes an item from cache | |
* @param key | |
* @returns {*} | |
*/ | |
remove(key) { | |
// If time has passed, remove the record from the cache | |
return this.db.removeItem(key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment