Skip to content

Instantly share code, notes, and snippets.

@guilbep
Created February 25, 2014 16:10
Show Gist options
  • Save guilbep/9211994 to your computer and use it in GitHub Desktop.
Save guilbep/9211994 to your computer and use it in GitHub Desktop.
Create $resource wrapper with retry and timeout
(function(window, angular, document, undefined) {
'use strict';
angular.module('mmResource', ['ng', 'ngResource']).
provider('mmResource', function(){
var common = this.common = {
retryTimeout : 4000,
retryMax: 3
};
// I want to override/wrap all the method generated by the $resource .. I managed don't see an another way to d
this.$get = ['$timeout', '$q', '$resource', function($timeout, $q, $resource) {
function resourceFactory(url, paramDefaults, actions) {
// create the resource to use in our wrapper
var ngResource = $resource(url, paramDefaults, actions);
var res = {};
var generateWrapper = function (methodName) {
return function(a1, a2, a3, a4){
var defer = $q.defer();
var inc = 0;
var args = arguments;
function retry(inc) {
inc += 1;
if (inc < common.retryMax) {
ngResource[methodName].apply(this, args).$promise.then(function(data){
defer.resolve(data);
}, function(error){
$timeout(function(){
retry(inc);
}, common.retryTimeout);
});
} else {
ngResource[methodName].apply(this, args).$promise.then(function(data){
defer.resolve(data);
}, function(error){
defer.reject(error);
});
}
}
retry(inc);
return {
"$promise": defer.promise
};
};
};
angular.forEach(ngResource.prototype, function(value, method){
// we slice(1) to delete the $
res[method.slice(1)] = generateWrapper(method.slice(1));
});
return res;
}
return resourceFactory;
}]
});
})(window, window.angular);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment