-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathretry.js
84 lines (77 loc) · 2.67 KB
/
retry.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* angular-hu-retry v1.1.0
* https://github.com/angular-hu/angular-hu
* (c) 2015 Telefónica I+D - http://www.tid.es
* @license MIT
*/
(function(angular) {
angular.module('httpu.retry', [])
.factory('huRetryInterceptorFactory', huRetryInterceptorFactory);
huRetryInterceptorFactory.$inject = ['$injector', '$q'];
function huRetryInterceptorFactory($injector, $q) {
return function(config) {
var configuration = {
/**
* Callback function called when a retry is about to be performed
* than can cancel the retry
* Useful when you don't want to retry a request based on some
* rejection parameters
*
* Must return a promise resolving to a boolean, allowing you
* to perform an async operation before retrying, or a boolean
* which means the desire of retrying
*
* It's called with the interceptors rejection
* https://docs.angularjs.org/api/ng/service/$http
*
* @returns {$q.defer().promise|Boolean}
* Resolves with the desire of retrying (as a boolean)
* Rejects when the request should not be retried
*/
shouldRetry: function retryAlways() {
return true;
},
/**
* The field to be looked in the config to determine
* how many retries are remaining. Defaults to 'retries'
*
* $httpProvider.interceptors.push(['huRetryInterceptorFactory', function(huRetryInterceptorFactory) {
* return huRetryInterceptorFactory({
* retryField: 'myretries'
* });
* }]);
*
* $http.get({
* myretries: 10
* })
* @type {String}
*/
retryField: 'retries'
};
angular.extend(configuration, config || {});
return {
responseError: function onResponseError(rejection) {
//should we retry?
var remaining = rejection.config[configuration.retryField];
if (remaining) {
return $q.when(configuration.shouldRetry(rejection)).then(
function(retry) {
if (retry) {
rejection.config[configuration.retryField] = --remaining;
//Get here the Service cause circular dependency
var $http = $http || $injector.get('$http');
return $http(rejection.config);
}
return $q.reject(rejection);
},
function() {
return $q.reject(rejection);
}
);
}
return $q.reject(rejection);
}
};
};
}
})(window.angular);