-
-
Save Eitz/869ae9908a27b96ca900bd136378d858 to your computer and use it in GitHub Desktop.
A function I made that wraps the node http.request function to make it a little more friendly. In my case I am using it for API route testing.
This file contains hidden or 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
// module dependencies | |
const http = require('http'); | |
const url = require('url'); | |
/** | |
* request - Wraps the http.request function making it nice for unit testing APIs. | |
* | |
* @param {string} reqUrl The required url in any form | |
* @param {object} options An options object (this is optional) | |
* @param {Function} cb This is passed the 'res' object from your request | |
* | |
*/ | |
var _request = function(reqUrl, options, cb){ | |
// incase no options passed in | |
if (typeof options === "function") { | |
cb = options; options = {}; | |
} | |
// parse url to chunks | |
reqUrl = url.parse(reqUrl); | |
// http.request settings | |
var settings = { | |
host: reqUrl.hostname, | |
port: reqUrl.port || 80, | |
path: reqUrl.pathname, | |
headers: options.headers || {}, | |
method: options.method || 'GET' | |
}; | |
// if there are params: | |
if (options.params) { | |
options.params = JSON.stringify(options.params); | |
settings.headers['Content-Type'] = 'application/json'; | |
settings.headers['Content-Length'] = options.params.length; | |
} | |
// MAKE THE REQUEST | |
const req = http.request(settings); | |
// if there are params: write them to the request | |
if (options.params) | |
req.write(options.params); | |
// when the response comes back | |
req.on('response', res => { | |
res.body = ''; | |
res.setEncoding('utf-8'); | |
// concat chunks | |
res.on('data', chunk => { res.body += chunk }); | |
// when the response has finished | |
res.on('end', () => { | |
// fire callback | |
cb(res.body, res); | |
}); | |
}); | |
// end the request | |
req.end(); | |
}; | |
// exporting the function | |
module.exports = { | |
request: _request | |
}; | |
/* | |
// Simple example (defaults to GET) | |
const simpleHttp = require('./node-simple-http'); | |
var simpleHttp.request('http://mysite.local:82/new-user', (body, res) => { | |
// do your stuff | |
}); | |
// More complex example 2 | |
simpleHttp.request('http://mysite.local:82/new-user', { | |
method: 'POST', | |
params:{ | |
name: 'Tester', | |
email: '[email protected]', | |
password: '****' | |
} | |
}, (body, res) => { | |
// do your stuff | |
}); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment