jmdobry / angular-cache

angular-cache is a very useful replacement for the Angular 1 $cacheFactory.
http://jmdobry.github.io/angular-cache
MIT License
1.39k stars 156 forks source link

Add ability to set "onExpire" function hook in cache configuration. #27

Closed jmdobry closed 11 years ago

jmdobry commented 11 years ago

When an item expires, (or when it is discovered that an item has expired in passive mode), optionally specify a callback function to be executed, which will be passed the key-value pair of the expired item. For example:

aggressive delete mode
var newCache = $angularCacheFactory('newCache', { 
  maxAge: 1000,
  aggressiveDelete: true,
  onExpire: function (key, value) {
    // do something, e.g. retrieve a fresh copy of the expired item from the server
  }
});

newCache.put('item1', 'foo');

// After 1 second, the "onExpire" function is executed.
// In this case, we don't have access to any return value from the "onExpire" callback, so don't rely on that. 
Passive delete mode (which is default)

This has to be handled differently:

var newCache = $angularCacheFactory('newCache', { 
  maxAge: 1000,
  onExpire: function (key, value, done) {
    // do something, e.g. retrieve a fresh copy of the expired item from the server
    done(); // when done, call done() and pass whatever you want into it
  }
});

newCache.put('item1', 'foo');

// ... wait 2 seconds

// Here it is discovered that item1 has expired, so it is deleted by angular-cache.
// Because an "onExpire" function was defined above, it is executed after item1 is deleted.
// Because this cache is in passive delete mode, we can capture a return value from the "onExpire" callback, which we couldn't do in aggressive delete mode.
// We capture the return value by passing in a callback to the get function, which is only executed if the item has expired.
$scope.item1 = newCache.get('item1', function (arg1, arg2, ...) {
  // This callback is the "done" function executed by the "onExpire" callback above.
  // Do something with whatever the "onExpire" callback gave to us.
});

With this feature, your cache can not only clear itself of expired items, but retrieve fresh copies as well (or whatever you want to do when the items expire).

CMCDragonkai commented 11 years ago

This feature has not be implemented yet right? I just spent the last 2 hours trying to understand why it wasn't working!

jmdobry commented 11 years ago

Sorry yes, this hasn't been implemented yet.

CMCDragonkai commented 11 years ago

Awesome. Any new on soft get?

jmdobry commented 11 years ago

I have not started on #30 yet.