-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
89 lines (81 loc) · 3.5 KB
/
index.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
85
86
87
88
89
'use strict';
const requestPromise = require('request-promise');
const Promise = require('bluebird');
const logger = require('./modules/logger')('request-promise-retry');
class rpRetry {
static _rpRetry(options) {
if (options.verbose_logging) {
logger.info(`calling ${options.uri} with retry ${options.retry}`);
}
const tries = options.retry || 1;
delete options.retry;
const delay = options.delay || 100; // default ms delay between retries
delete options.delay;
const factor = options.factor || 1; // If absent, delay will always be the same.
delete options.factor;
if (options.verbose_logging) {
logger.info(`calling ${options.uri} with retry ${tries}, initial delay=${delay}, factor=${factor}`);
}
const fetchDataWithRetry = (tryCount, delay) => {
return requestPromise(options)
.then(result => {
if (options.verbose_logging) {
logger.info(`Result obtained for ${options.method} request to ${options.uri}`);
}
return Promise.resolve(result);
})
.catch(err => {
err.accepted = false;
if (options.accepted && options.accepted.indexOf(err.statusCode) > -1) {
err.accepted = true;
return Promise.reject(err);
}
logger.info(`Encountered error ${err.message} for ${options.method} request to ${options.uri}, retry count ${tryCount}`);
tryCount -= 1;
if (tryCount) {
return new Promise((resolve, reject) => {
setTimeout(() => {
logger.debug(`waiting for ${delay} ms before next retry for ${options.uri}. Next wait ${delay * factor}`);
return resolve(fetchDataWithRetry(tryCount, delay * factor));
}, delay);
});
}
return Promise.reject(err);
});
};
return fetchDataWithRetry(tries, delay);
}
static _rp(options) {
if (options.verbose_logging) {
logger.info(`calling ${options.uri} without retries`);
}
return requestPromise(options)
.then(result => {
if (options.verbose_logging) {
logger.info(`Result obtained for ${options.method} request to ${options.uri}`);
}
return Promise.resolve(result);
})
.catch(err => {
logger.info(`Encountered error ${err.message} for ${options.method} request to ${options.uri}`);
return Promise.reject(err);
});
}
static rp(options) {
if (options.retry) {
if (typeof options.retry === 'number') {
if (options.retry < 0) {
return Promise.reject(new Error(`Retry count must be positive integer`));
}
return rpRetry._rpRetry(options);
} else if (typeof options.retry === 'boolean') {
options.retry = 1;
return rpRetry._rpRetry(options);
} else {
return Promise.reject(new Error(`Supports boolean or positive integer`));
}
}
return rpRetry._rp(options);
}
}
module.exports = rpRetry.rp;