Monday, July 29, 2013

Caching with Angular JS (LRU, MaxAge, etc)



When working with Angular JS, it is many times desirable to minimize client-server interaction where it's not mandatory. 

If you are hosting a web service on App Engine, this could save you some serious $$$, and at any case, it would be faster for your clients to read the data from the a client stored source (in-memory, localStorage or any other browser based cache) then to get it from a remote server Ajax call. 

For this purpose, Angular JS exposes the option to implement a $cacheFactory. However, the built in caching mechanism, to this point, does not include out of the box support for things like LRU Cache and Max Size Cache

Luckily we have Angular-cache (project maintained by jmdobry) which gives that, plus a few more neat cachers. 

Before:

.factory('featuresData', function ($http, $location) {
        return{
            all:function () {
                return $http({
                    url:'/api/features',
                    method:'GET'
                })
            }           
    })

After:

.factory('featuresData', function ($http, $location,$angularCacheFactory) {
        return{
            cache: $angularCacheFactory('maxAgeCache', { maxAge: 4000 }),
            all:function () {
                if (!this.cache.get('all')) {
                    this.cache.put('all', $http({
                        url:'/api/features',
                        method:'GET'
                    }));
                }
                return this.cache.get('all');
            }        
        }


Enjoy!

No comments:

Post a Comment