From ff6ba434b6d91b6a4a4e9b3a7fbb8cadced229ad Mon Sep 17 00:00:00 2001 From: Jack Lucas Date: Wed, 10 May 2017 01:48:41 +0000 Subject: Post-R1 API & other updates. Change-Id: Id0e2e15b95a5713a25a746534fc40b56599a5f06 Signed-off-by: Jack Lucas --- lib/promise_request.js | 54 +++++++++++++++++++++++++++++++++++++------------- 1 file changed, 40 insertions(+), 14 deletions(-) (limited to 'lib/promise_request.js') diff --git a/lib/promise_request.js b/lib/promise_request.js index 906c16c..5a97bba 100644 --- a/lib/promise_request.js +++ b/lib/promise_request.js @@ -19,26 +19,53 @@ See the License for the specific language governing permissions and limitations "use strict"; /* - * Make an HTTP request using a string or a readable stream for the body + * Make an HTTP request using a string for the body * of the request. * Return a promise for result in the form * {status: , body: } */ -const stream = require('stream'); -const request = require('request'); +const http = require('http'); +const https = require('https'); +const url = require('url'); +const querystring = require('querystring'); -let logger = null; +var logger = null; exports.doRequest = function(options, body) { + return new Promise(function(resolve, reject) { + + var reqBody = null; + if (options.json) { + reqBody = JSON.stringify(options.json); + options.headers = options.headers || {}; + options.headers['Content-Type'] = 'application/json'; + } + else if (body) { + reqBody = body; + } + + if (options.uri) { + var parsed = url.parse(options.uri); + options.protocol = parsed.protocol; + options.hostname = parsed.hostname; + options.port = parsed.port; + options.path = parsed.path; + if (options.qs) { + options.path += ('?' + querystring.stringify(options.qs)); + } + } logger.debug("doRequest: " + JSON.stringify(options)); - if (body && !(body instanceof stream.Readable)) { - // Body is a string, just include it in the request - options.body = body; + + try { + var req = (options.protocol === 'https:' ? https.request(options) : http.request(options)); + } + catch (e) { + logger.debug('Error constructing request: ' + e); + reject(e); } - var req = request(options); // Reject promise if there's an error req.on('error', function(error) { @@ -88,13 +115,12 @@ exports.doRequest = function(options, body) { } }); }); - - // If there's a readable stream for a body, pipe it to the request - if (body && (body instanceof stream.Readable)) { - // Pipe the body readable stream into the request - body.pipe(req); + + if (reqBody) { + req.write(reqBody, 'utf8'); } - }); + req.end(); + }); }; exports.setLogger = function(logsource) { -- cgit 1.2.3-korg