Skip to content

Instantly share code, notes, and snippets.

@andreialecu
Last active November 16, 2016 23:32
Show Gist options
  • Save andreialecu/0477f0949b8258dffea8cf63d79f473d to your computer and use it in GitHub Desktop.
Save andreialecu/0477f0949b8258dffea8cf63d79f473d to your computer and use it in GitHub Desktop.
dpd redis cache
if(!ctx.server.redisClient) {
var redis = require('redis');
ctx.server.redisClient = redis.createClient(global.process.env.REDIS_URL);
}
if (!internal || !query.key) return;
//console.log('cache getting', query.key);
$addCallback();
ctx.server.redisClient.get(query.key, function(err, value) {
if (err || !value) {
ctx.res.statusCode = 404;
$finishCallback();
return;
}
//console.log('got redis cache item for', query.key, value.length);
setResult(JSON.parse(value));
$finishCallback();
});
if(!ctx.server.redisClient) {
var redis = require('redis');
ctx.server.redisClient = redis.createClient(global.process.env.REDIS_URL);
}
if (!internal || !body.key) return;
console.log('cache setting', body.key);
$addCallback();
ctx.server.redisClient.set(body.key, JSON.stringify(body.data), function(err) {
if (err) {
console.error(err);
}
ctx.server.redisClient.expire(body.key, 60); // expire key in 60 seconds
setResult(body.data);
$finishCallback();
});
@andreialecu
Copy link
Author

andreialecu commented Nov 16, 2016

Create a dpd-event with the above code, name it 'cache'.

Use it like:

dpd.cache.get({key: 'some cache key'}).catch(err => { 
  // oops, not cached, cache it now... 
  var data = computeExpensiveValue();
  return dpd.cache.post({key: 'some cache key', data: data })
}).then(expensiveValue => { 
  // do something with the cached value, which will now be cached as well

})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment