cache
simple object based caching
npm install @amphibian/cache
var createCache = require('@amphibian/cache');
var userCache = createCache();
userCache.set('user-123', {id: '123', name: 'Some Name'});
console.log(userCache.get('user-123')); // > {id: '123', name: 'Some Name'}
// Invalidate a single cache key
userCache.invalidate('user-123');
// Invalidate the entire cache
userCache.invalidate();
// Get the entire cache object
console.log(userCache.contents()); /* > {
'user-123': {
tag: null,
value: {
id: '123',
name: 'Some Name'
}
}
*/
Cache lifetime
Data prone to change should always have a set lifetime to avoid having stale data lying around. Set the Number
of milliseconds as lifetime
in the options
object.
userCache.set('user-123', {id: '123', name: 'Some Name'}, {
lifetime: 300 * 1000 // 5 minutes
});
// Assert cache freshness
userCache.fresh('user-123'); // > true
Tagging cache
Setting tags for the cache can be useful, for example, when the data returned is an error. This way you can keep handling the error like you normally would. Set the tag as a String
tag
in the options
object.
userCache.set('user-123', {error: 'No user found'}, {
tag: 'error'
});
userCache.tag('user-123'); // > 'error'
Open a cache
var user123Cache = userCache.open('user-123');
user123Cache.set({id: '123', name: 'Some New Name'});
Cache options
When creating a cache you can give an options
Object
as the first argument.
var userCache = createCache();
options.enabled
(Boolean
)
Enable or disable the cache. Useful during tests.