UNPKG

2.27 kBJavaScriptView Raw
1function RetryOperation(timeouts) {
2 this._timeouts = timeouts;
3 this._fn = null;
4 this._errors = [];
5 this._attempts = 1;
6 this._operationTimeout = null;
7 this._operationTimeoutCb = null;
8 this._timeout = null;
9}
10module.exports = RetryOperation;
11
12RetryOperation.prototype.retry = function(err) {
13 if (this._timeout) {
14 clearTimeout(this._timeout);
15 }
16
17 if (!err) {
18 return false;
19 }
20
21 this._errors.push(err);
22
23 var timeout = this._timeouts.shift();
24 if (timeout === undefined) {
25 return false;
26 }
27
28 this._attempts++;
29
30 var self = this;
31 setTimeout(function() {
32 self._fn(self._attempts);
33
34 if (self._operationTimeoutCb) {
35 self._timeout = setTimeout(function() {
36 self._operationTimeoutCb(self._attempts);
37 }, self._operationTimeout);
38 }
39 }, timeout);
40
41 return true;
42};
43
44RetryOperation.prototype.attempt = function(fn, timeoutOps) {
45 this._fn = fn;
46
47 if (timeoutOps) {
48 if (timeoutOps.timeout) {
49 this._operationTimeout = timeoutOps.timeout;
50 }
51 if (timeoutOps.cb) {
52 this._operationTimeoutCb = timeoutOps.cb;
53 }
54 }
55
56 this._fn(this._attempts);
57
58 var self = this;
59 if (this._operationTimeoutCb) {
60 this._timeout = setTimeout(function() {
61 self._operationTimeoutCb();
62 }, self._operationTimeout);
63 }
64};
65
66RetryOperation.prototype.try = function(fn) {
67 console.log('Using RetryOperation.try() is deprecated');
68 this.attempt(fn);
69};
70
71RetryOperation.prototype.start = function(fn) {
72 console.log('Using RetryOperation.start() is deprecated');
73 this.attempt(fn);
74};
75
76RetryOperation.prototype.start = RetryOperation.prototype.try;
77
78RetryOperation.prototype.errors = function() {
79 return this._errors;
80};
81
82RetryOperation.prototype.attempts = function() {
83 return this._attempts;
84};
85
86RetryOperation.prototype.mainError = function() {
87 if (this._errors.length === 0) {
88 return null;
89 }
90
91 var counts = {};
92 var mainError = null;
93 var mainErrorCount = 0;
94
95 for (var i = 0; i < this._errors.length; i++) {
96 var error = this._errors[i];
97 var message = error.message;
98 var count = (counts[message] || 0) + 1;
99
100 counts[message] = count;
101
102 if (count >= mainErrorCount) {
103 mainError = error;
104 mainErrorCount = count;
105 }
106 }
107
108 return mainError;
109};
\No newline at end of file