UNPKG

1.13 kBJavaScriptView Raw
1var retries = require('./retries');
2
3
4/**
5 * Add to the request prototype.
6 */
7
8module.exports = function (superagent) {
9 var Request = superagent.Request;
10 Request.prototype.retry = retry;
11};
12
13
14/**
15 * Export retries for extending
16 */
17
18module.exports.retries = retries;
19
20
21/**
22 * Sets the amount of times to retry the request
23 * @param {Number} count
24 */
25
26function retry (retries) {
27
28 var self = this
29 , oldEnd = this.end;
30
31 retries = retries || 1;
32
33 this.end = function (fn) {
34
35 function attemptRetry () {
36 return oldEnd.call(self, function (err, res) {
37 if (!retries || !shouldRetry(err, res)) return fn && fn(err, res);
38
39 // HACK: reset the internal state
40 self.abort();
41 delete self.req;
42 self.called = false;
43
44 retries--;
45 return attemptRetry();
46 });
47 }
48
49 return attemptRetry();
50 };
51}
52
53
54/**
55 * Determine whether we should retry based upon common error conditions
56 * @param {Error} err
57 * @param {Response} res
58 * @return {Boolean}
59 */
60
61function shouldRetry (err, res) {
62 return retries.some(function (check) { return check(err, res); });
63}
\No newline at end of file