jaredwray/cacheable

Set different TTL for different functions

Closed this issue · 3 comments

Hey

Firstly just want to say this is a really cool module

I was thinking it might be nice to be able to set a different TTL for different cached functions

e.g.

var getShortLivedField = function(id, callback) {
  ...
}

var getLongLivedField = function(id, callback) {
  ...
}

app.get('/short/lived', function(req, res) {
  var cache_key = "short:" + req.params.id;
  var ttl = 1;
  cache.wrap(cache_key, ttl, function(cache_cb) {
    getShortLivedField(req.params.id, cache_cb);
  }, function(err,result){
    res.send(result);
  });
})

app.get('/long/lived', function(req, res) {
  var cache_key = "long:" + req.params.id;
  var ttl = 600;
  cache.wrap(cache_key, ttl, function(cache_cb) {
    getLongLivedField(req.params.id, cache_cb);
  }, function(err,result){
    res.send(result);
  });
})

This could stay backwards compatible by checking the arguments types in the cache.wrap function

This would work well with redis and other stores but probably not with the lru-cache as that seems to have a global TTL

or would you suggest that is better to create a custom redis store that has a map of TTL to keys
then depending on the key that is passed in, the correct ttl can be used?

Happy to help out with any changes if needed?

Thanks! Yeah, I think this is a good feature and is long overdue. If you want to give it a shot, please do. Otherwise I can probably work on it next week.

cool thanks,

I started having a go at it but wanted to ask your preference on a few decisions

Would you expect each store to have a set function that has the signature set(key, ttl, data, callback) or would you have each store implement a new function say setWithTTL(key, ttl, data, callback) and keep the set function as set(key, data, callback)?

As the lru-cache doesn't support having different ttl's for different keys, would you expect an error if you try to set a ttl in the wrap function when using the memory store?
Or would you silently just use the ttl that was sent in to initialise the store?

Good questions. I think for the signature I'd do:
set(key, data, ttl, cb)
(ttl as last arg before callback)

I think to handle stores that don't take a ttl arg, just let all the args pass to the underlying store and let them throw an error. Otherwise you'd have to add different checks for different stores. In other words, it's up to the user to make sure they don't pass in unsupported args. The LRU cache is really only included in this library so that there's some kind of default cache available. I figure most people use this library with redis, memcache, etc., but maybe I'm wrong.