Suppose I have a service that retrieves a list of tags and I store tags in the cache:
function TagsRetriever() {
var cache = $cacheFactory("tags");
function getTags() {
var cached = cache.get("tags");
if (cached) {
return cached;
} else {
return $http.get("url/getTags").then(function (tags) {
cache.put("tags", tags);
});
}
}
}
What is the common approach to invalidate the cache? Should I compare it to current date? Does angular provide any mechanism of cache invalidation?
And what's the benefit of using cacheFactory instead of a variable holding cache?
cacheFactory basically gives you a place to store stuff in memory as a service. It provides an interface to interact with the cache, and it is available anywhere you inject the service.
It doesn't appear to have anything specific for doing invalidation. Just include a date key whenever you put() and check against it.
Oliver's usage is excellent as well. Stream data to the cache through sockets and then just get from the cache. If you aren't doing it this way though, you could create a service that handles the cache validation. Pass the data to the service. If it's new data, it adds a date key. If it's existing data, compare dates.
It has the following methods:
There really isn't much to it: Documentation
You may check brilliant angular-cache which will keep you from re-inventing the wheel with $cacheFactory (it provides nothing but simple storage, sometimes it's enough).
That's how it handles cache invalidation (an example from the manual):
CacheFactory('profileCache', {
maxAge: 60 * 60 * 1000 // 1 hour,
deleteOnExpire: 'aggressive',
onExpire: function (key, value) {
$http.get(key).success(function (data) {
profileCache.put(key, data);
});
}
});
And what's the benefit of using cacheFactory instead of a variable holding cache?
Besides it establishes testable service that implements LRU and saves you a few lines of code? Nothing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With