

cashbox
javascript cache library with configurable storage
npm install cashbox
Cashbox provides a common caching api on top of pluggable backend stores. memory and redis are currently the two supported stores, with memory being the default. Cashbox
fully supports custom stores as long as they implement the correct api (see the memory store for an example of what to implement).
Using cashbox is pretty simple:
var Cashbox = require('cashbox');
var cache = new Cashbox();
cache.set('myKey', 'myValue', function(err, wasSet) {
cache.get('myKey', function(err, value) {
console.log(value);
});
});
cache.set('myKey', 'myValue', 10, function(err, wasSet) {
});
cache.set('myKey', 'myValue', '1 hour', function(err, wasSet) {
});
Cashbox API
Cashbox(config) constructor
The Cashbox
constructor accepts an optional config object
- type can be set to specify cache store type.
memory
is the default, redis
is also supported - store can be set to either an instance, or a constructor for a backend cache store. The constructor will be passed the config object should it need any special configuration.
var myCustomStore = new MyCustomStore();
var cache = new Cashbox({ store: myCustomStore });
cache = new Cashbox({ store: MyCustomStore, foo: 'bar' });
- host can be set for
redis
store. Defaults to localhost
- port can be set for
redis
store. Defaults to 6379
- options can be set for
redis
store. These are connection options passed into the redis.createClient(host, port, options)
call.
.get(key, load, ttl, callback)
- key is a string value used as the cache key
- load - Optionally pass a
load
function that will be called upon a cache miss.
function load(key, cb) {
doSomethingAsync(key, function(err, value) {
if(err) return cb(err);
cb(null, value);
});
}
cache.get(key, load, function(err, v) {
console.log(v);
});
- ttl is also optional, and may be specified w/ or w/o a load function. Supported formats for ttl are either a value in seconds, or a time string parseable by timestr (i.e. "1 hour")
- callback is called upon completion of fetching the value from the cache store. It is passed an error first, and the value.
undefined
is returned on cache misses