diff --git a/lib/utils.js b/lib/utils.js index 24b1f87..0171b78 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -13,13 +13,13 @@ var http = require('http'), module.exports.request = function(options) { return new Promise(function(resolve, reject) { - var opts = { service: 'apigateway', region: options.region, method: options.method, path: options.path }; + if (options.body) opts.body = JSON.stringify(options.body); opts = aws4.sign(opts, { @@ -27,42 +27,61 @@ module.exports.request = function(options) { secretAccessKey: options.secretAccessKey }); - var req = https.request(opts, function(res) { + var request = function () { + return new Promise(function(resolve, reject){ + var req = https.request(opts, function(res) { + var body = ''; - var body = ''; + res.on('data', function(d) { + body += d; + }); - res.on('data', function(d) { - body += d; - }); + res.on('end', function() { + resolve({ + "statusCode": res.statusCode, + "body": body + }); + }); + }); - res.on('end', function() { + req.on('error', function(e) { + // General error, i.e. + // - ECONNRESET - server closed the socket unexpectedly + // - ECONNREFUSED - server did not listen + // - HPE_INVALID_VERSION + // - HPE_INVALID_STATUS + reject(e); + }); + if (options.body) req.write(JSON.stringify(options.body)); + req.end(); + }); + }; + + var handle = function(){ + request().then(function (res) { if (~[200,201,203,205,206].indexOf(res.statusCode)) { // Successful w/ Body - resolve(JSON.parse(body)); + resolve(JSON.parse(res.body)); } else if (~[202,204].indexOf(res.statusCode)){ //Successful w/o Body resolve({ message:"Request is processing" }); + } else if (~[429].indexOf(res.statusCode)){ + //Too Many Requests + setTimeout( handle, 5000 ); } else { - body = JSON.parse(body); + var body = JSON.parse(res.body); body.statusCode = res.statusCode; reject(body); } - }); - }); - req.on('error', function(e) { - // General error, i.e. - // - ECONNRESET - server closed the socket unexpectedly - // - ECONNREFUSED - server did not listen - // - HPE_INVALID_VERSION - // - HPE_INVALID_STATUS - reject(e); - }); + },function(err){ + reject( err ); + }); + }; - if (options.body) req.write(JSON.stringify(options.body)); - req.end(); + handle(); }); -} +};