Skip to content

Commit

Permalink
async retry strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
smarth55 committed Dec 24, 2019
1 parent 01fa712 commit 4f6d0e8
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,24 @@ function myRetryStrategy(err, response, body, options){
}
}

/**
* With an asynchronous retry strategy
* @param {Null | Object} err
* @param {Object} response
* @param {Object} body
* @param {Object} options copy
* @return {Object} mustRetry: {Boolean} true if the request should be retried
* options: {Object} new options for request
*/
async function myRetryStrategy(err, response, body, options){
let token = await getNewApiAuthToken();
options.headers = {'Authorization': `Bearer ${token}`}
return {
mustRetry: true,
options: options, // retry with new auth token
}
}

request({
url: 'https://api.domain.com/v1/a/b'
json:true,
Expand Down
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ Request.prototype._tryUntilFail = function () {
this.maxAttempts--;
this.attempts++;

this._req = Request.request(this.options, function (err, response, body) {
this._req = Request.request(this.options, async function (err, response, body) {
if (response) {
response.attempts = this.attempts;
}
Expand All @@ -130,7 +130,7 @@ Request.prototype._tryUntilFail = function () {
err.attempts = this.attempts;
}

var mustRetry = this.retryStrategy(err, response, body, _.cloneDeep(this.options));
var mustRetry = await Promise.resolve(this.retryStrategy(err, response, body, _.cloneDeep(this.options)));
if (_.isObject(mustRetry) && _.has(mustRetry, 'mustRetry')) {
if (_.isObject(mustRetry.options)) {
this.options = mustRetry.options; //if retryStrategy supposes different request options for retry
Expand Down
19 changes: 19 additions & 0 deletions test/strategies.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,25 @@ describe('RetryStrategies', function () {
done();
});
})

it('should work with an async strategy', function (done) {
var strategy = function (err, response, body) {
return new Promise(function(resolve, reject) {
setTimeout(function () {resolve({mustRetry: false})}, 500);
});
};

request({
url: 'http://www.filltext.com/?rows=1',
maxAttempts: 2,
retryDelay: 100,
retryStrategy: strategy
}, function(err, response, body) {
if(err) done(err);
t.strictEqual(1, this.attempts); // maxAttempts NOT reached
done();
});
});
});
});

Expand Down

0 comments on commit 4f6d0e8

Please sign in to comment.