Permalink
Browse files

Wrapper for http client (found on the web)

  • Loading branch information...
balis committed May 17, 2012
1 parent faf4ad4 commit d6f63e8f97fc094b0a67c5e7f847b5e72d5b4bce
Showing with 84 additions and 0 deletions.
  1. +84 −0 req_url/reqUrl.js
View
@@ -0,0 +1,84 @@
+// module dependencies
+var http = require('http'),
+ url = require('url');
+
+
+ /**
+ * UrlReq - 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
+ *
+ */
+exports.urlReq = function(reqUrl, options, cb){
+ if(typeof options === "function"){ cb = options; options = {}; }// incase no options passed in
+
+ // 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
+ var 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', function(res){
+ res.body = '';
+ res.setEncoding('utf-8');
+
+ // concat chunks
+ res.on('data', function(chunk){ res.body += chunk });
+
+ // when the response has finished
+ res.on('end', function(){
+
+ // fire callback
+ cb(res.body, res);
+ });
+ });
+
+ // end the request
+ req.end();
+}
+
+
+// Simple Example (defaults to GET)
+mylib.urlReq('http://mysite.local:82/newUser', function(body, res){
+
+ // do your stuff
+
+});
+
+
+
+// More complex Example 2
+mylib.urlReq('http://mysite.local:82/newUser', {
+ method: 'POST',
+ params:{
+ name: 'Tester',
+ email: 'Tester@example.com',
+ password: 'password'
+ }
+}, function(body, res){
+
+ // do your stuff
+
+});

0 comments on commit d6f63e8

Please sign in to comment.