AngularJS Decorator $http prevent multiple request to the same url

Caching request promises to prevent multiple request to the same url

by ref

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.28/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/restangular/1.4.0/restangular.js"></script>
<div ng-app="myApp">
    AngularJS Decorator $http
    <br/>
    Caching request promise to prevent multiple request to the same url
    <br/>
    Fast click on button
    <hr/>
    <button ng-click="retrieveData()">Request data</button>
    <hr/>
    <span>Click count: {{clickCount}}</span><br/>
    <span>Request count: {{requestCount}}</span><br/>
    <span>Result: {{result | json}}</span>
</div>

JavaScript

var myApp = angular.module('myApp', ['restangular']);

myApp.factory('myService', function (Restangular) {
  return Restangular.service('myService');
});

myApp.config(function ($provide, RestangularProvider) {
    RestangularProvider.setBaseUrl('http://echo.jsontest.com/');
    
    $provide.decorator('$http', function ($delegate, $cacheFactory, $rootScope, $timeout) {
        var $http = $delegate;
        var customCache = $cacheFactory('customCache');
        var wrapper = function () {
            var key = arguments[0].url;
            var requestPromise = customCache.get(key);
            if (!requestPromise){
                $rootScope.requestCount++;
                requestPromise = $http.apply($http, arguments);
                requestPromise.then(function(){
                    //caching for 1 second
                    $timeout(function(){
		                customCache.remove(key);
                    }, 1000);
                });
                customCache.put(key, requestPromise)
            }
            return requestPromise;
        };
        
        Object.keys($http).filter(function (key) {
            return (typeof $http[key] === 'function');
        }).forEach(function (key) {
            wrapper[key] = function () {
                return $http[key].apply($http, arguments);
            };
        });
        
        return wrapper;
    });
});

myApp.run(function ($rootScope, myService) {   
    $rootScope.result = {};
    $rootScope.clickCount = 0;
    $rootScope.requestCount = 0;
    $rootScope.retrieveData = function(){
        $rootScope.clickCount++;
        var url = myService.one('isCool').one('two').one('three');
        url.get().then(function(res){
            $rootScope.result = res.plain();
        });
    }
});