Skip to content

Instantly share code, notes, and snippets.

@shabin-slr
Last active August 3, 2017 11:15
Show Gist options
  • Save shabin-slr/9c78bf1010c3754e517a942b6ae301df to your computer and use it in GitHub Desktop.
Save shabin-slr/9c78bf1010c3754e517a942b6ae301df to your computer and use it in GitHub Desktop.
An HTTPS REST client for NodeJS apps.
const https = require('https');
/**
*
* @param {String} host eg. : 'graph.facebook.com'
* @param {String} endPoint
* @param {String} method eg. : 'GET', 'POST' etc
* @param {Object} requestOptions = {
* @param {Object} headers eg. : {'Content-Type' : 'application/json'}
* @param {String} body eg. : 'Request body'
* }
*/
let makeRequest = (host, endPoint, method, requestOptions={}) => {
return new Promise ( (resolve, reject) =>{
if(!!requestOptions.body){
requestOptions.headers = requestOptions.headers || {};
requestOptions.headers['Content-Length'] = requestOptions.body.length;
}
var options = {
hostname: host,
port: 443,
path: endPoint,
method: method,
headers : requestOptions.headers || {}
};
var req = https.request(options, function(response) {
let body = "";
response.on('data', (d) => {
body += d;
});
response.on('end', function() {
resolve({
statusCode : response.statusCode,
body : body
})
});
response.on('error', function() {
reject("Error while making request");
});
});
if(!!requestOptions.body){
req.write(requestOptions.body);
}
req.on('error', (e) => {
console.error("ERROR WHILE MAKING API call to " + host + " : ", e)
reject(e);
});
req.end();
})
}
module.exports = {
makeRequest : makeRequest
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment