Proper cache invalidation
This is a question
I was wondering is there a common approach for CRUD operations with restangular. I have cache turned on on $http and when I edit some particular item it is still not changed in the places where it was listed with getList().
So I think of 2 ways: 1st invalidation of all cache seems not very usefull, there are lot of stuff that is not changed I would want to stay in cache
2nd to have some middleware between restangular and controllers, controllers would get items from this middleware and middleware would full-fill it with restangular.
but I don't want to write something that exists, so if there are some recommended solution please comment.
Hi @fuksito
I get what you mean. There's no way in Restangular of actually doing this. What I currently have coded is the following in my apps:
var cache = $cacheFactory('http');
Restangular.setDefaultHttpFields({cache: cache});
Restangular.setResponseInterceptor(function(response, operation) {
if (operation === 'put' || operation === 'post' || operation === 'delete') {
cache.removeAll();
}
return response;
});
};
That way, I remove all in the cache if there's a delete, post or put. It's not ideal but it's the quicker way.
If you do implement this, can you please share this? I've created a repository https://github.com/mgonto/restangular-plugins that I plan to fill with user made plugins for Restangular to make other users life easier :). It may actually help #25
If you're interested, I can create the issue on restangular-plugins and then you can submit it. I'll first create the structure for the whole app so that you can submit the PR easily :).
Thanks!
There remains the problem that the data may have changed in another user's browser or on the server via other processes. For client side caching the following use-cases come to mind: (a) cache read only data (data that almost never changes, i.e. reference data) (b) cache data for a short period of time; the cache entry is invalidated after an expiration time (something like 5 to 30 seconds). This really helps with handling bursty requests for the same data (perhaps coming from different controllers. (c) as mentioned above, the cache entry should be invalidated when a PUT, POST, DELETE, or PATCH is invoked.
Short note on the solution mentioned by @mgonto: works fine, but the operation for delete seems to be remove.