Cache values in memory
CACHE is an in-memory key-value store with expiration. CACHE.set(key, value, expire) stores a value (the expiration is a text such as '10 seconds' or '5 minutes', default '5 minutes'). CACHE.get(key, default) returns the value, or the default once it has expired. CACHE.remove(key) deletes one key and CACHE.reset(search) deletes every key that contains the text.
Use it for results that are expensive to compute and may be a little stale. The cache lives in the process: it is cleared on restart and is not shared between processes.
exports.install = function() {
ROUTE('GET /slow/', slow);
ROUTE('DELETE /slow/', clear);
};
var computed = 0;
function slow($) {
var cached = CACHE.get('slow-result');
if (cached) {
$.json({ value: cached, cached: true, computed: computed });
return;
}
computed++;
var value = 'result-' + computed;
CACHE.set('slow-result', value, '1 second');
$.json({ value: value, cached: false, computed: computed });
}
function clear($) {
CACHE.remove('slow-result');
$.json({ ok: true });
}