Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalidate $resource Cache After Post Request

I am using $resource and caching the results of get requests. My problem is that, after post requests, the cache is not being invalidated.

Here is the return value from the service:

return $resource('http://url.com/api/url/:id', {}, {
'query' : {
      method : 'GET',
      isArray:true,
      cache : true
    },
'get' : {
  method : 'GET',
  cache : false
}  
})

Here is the save method I am using inside my controller. As you can see, I'm using the callback on the post request to recalculate the query/list of nouns.

var newNoun = new Noun($scope.noun);
newNoun.$save(function(x) {
  $scope.nouns = Noun.query();
});

I would like to invalidate the cache after calling post or another non-get method. How could I do this? Is this already built into $resource or do I need to implement it on my own?

like image 550
inperspective Avatar asked Aug 04 '14 11:08

inperspective


People also ask

When should you invalidate cache?

extra is associated with the CSV file, cache will be invalidated when the file is changed (because the cache key will be different). Another example is one code chunk using a variable created from a previous code chunk. When the variable is updated in the previous chunk, this chunk's cache should be invalidated, too.

Why do we need cache invalidation?

Cache invalidation describes the process of actively invalidating stale cache entries when data in the source of truth mutates. If a cache invalidation gets mishandled, it can indefinitely leave inconsistent values in the cache that are different from what's in the source of truth.


1 Answers

You could create a wrapper service to do the caching like you want, for example:

app.factory('cachedResource', function ($resource, $cacheFactory) {
  var cache = $cacheFactory('resourceCache');

  var interceptor = {
    response: function (response) {
      cache.remove(response.config.url);
      console.log('cache removed', response.config.url);
      return response;
    }
  };

  return function (url, paramDefaults, actions, options) {
    actions = angular.extend({}, actions, {
      'get':    { method: 'GET', cache: cache },
      'query':  { method: 'GET', cache: cache, isArray: true },
      'save':   { method: 'POST', interceptor: interceptor },
      'remove': { method: 'DELETE', interceptor: interceptor },
      'delete': { method: 'DELETE', interceptor: interceptor },
    });

    return $resource(url, paramDefaults, actions, options);
  };
});

Then replace any $resource with cachedResource.

Example plunker: http://plnkr.co/edit/lIQw4uogcoMpcuHTWy2U?p=preview

like image 78
runTarm Avatar answered Sep 21 '22 17:09

runTarm