Skip to content

Instantly share code, notes, and snippets.

@ceccode
Last active July 26, 2016 15:26
Show Gist options
  • Select an option

  • Save ceccode/e4b7c4c5a3bd1d6a97b043952cc72d64 to your computer and use it in GitHub Desktop.

Select an option

Save ceccode/e4b7c4c5a3bd1d6a97b043952cc72d64 to your computer and use it in GitHub Desktop.
Simple module that wrap nodejs http.request api.
"use strict";
const http = require('http');
const util = require('util');
const querystring = require('querystring');
function addQueryString(data) {
return (data !== "") ? querystring.stringify(data) : '';
}
function performRequest(options, endpoint, method, data, success, error) {
let dataString = JSON.stringify(data);
options = Object.assign(options, {
path: endpoint,
method: method
});
if (!options.headers) {
options.headers = {}
}
if (method == 'GET') {
options.path = endpoint + addQueryString(data);
} else {
options.headers = Object.assign(options.headers, {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(dataString, 'utf-8')
});
}
let req = http.request(options, (res) => {
res.setEncoding('utf-8');
let responseString = '';
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
responseString += chunk;
});
res.on('end', () => {
try {
let responseObject = null;
if (typeof responseString === 'string') {
responseObject = JSON.parse(responseString);
}
success(responseObject);
} catch (err) {
console.log(`Catch error: ${err.message}`);
error(err);
}
});
});
req.on('error', (e) => {
console.log(`Problem with request: ${e.message}`);
error(e);
});
if (method !== 'GET' && dataString) {
req.write(dataString);
}
req.end();
}
module.exports = performRequest;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment