Created
April 22, 2012 03:37
-
-
Save polotek/2447285 to your computer and use it in GitHub Desktop.
A node http client that adds things like retry behavior
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var request = require('request') | |
, retry = require('retry') | |
, httpLog = log4js.getLogger('httpLog'); | |
var HTTPClient = { | |
defaultOpts: { | |
, request: { | |
headers: { | |
Host: 'paddie' | |
, 'Content-Type': 'application/javascript' | |
} | |
} | |
, retry: { | |
retries: 2 | |
, factor: 10 // backoff by factors of 10 | |
, minTimeout: 100 // wait at least 100 ms between retries | |
, maxTimeout: 500 // max time between retries | |
, randomize: false // don't randomize times | |
} | |
} | |
, request: function(opts, callback) { | |
var op = retry.operation(defaultOpts.retry); | |
opts = merge({}, defaultOpts.request, opts); | |
op.attempt(function(tries) { | |
if(tries > 1) { | |
runtimeLog.debug('... retrying'); | |
} | |
request(opts, function(err, res, data) { | |
var status = res ? res.statusCode : 0; | |
httpLog.info('CLIENT_REQUEST ' + opts.url + ' ' + status ); | |
// done retrying | |
if(!err && status >= 200 && status < 300) { | |
runtimeLog.info('Activated ' + pad.id); | |
return callback(null, true); | |
} else { | |
// maybe retry | |
var expectRetry = err || | |
new Error('request failed: ' + status); | |
if(op.retry(expectRetry)) { return; } | |
err = op.mainError(); | |
return callback(err, false); | |
} | |
}); | |
}); | |
} | |
, get: function(opts, callback) { | |
opts.method = 'GET'; | |
return this.request(opts, callback); | |
} | |
, post: function(opts, callback) { | |
opts.method = 'POST': | |
return this.request(opts, callback); | |
} | |
} | |
module.exports = HTTPClient; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment