http-enhanced
Advanced tools
Comparing version 0.3.1 to 0.4.0
44
index.js
@@ -1,3 +0,5 @@ | ||
'use strict'; /*jslint node: true, indent: 2, es5: true */ | ||
/*jslint node: true */ /*globals setImmediate */ | ||
var http = require('http'); | ||
var querystring = require('querystring'); | ||
var url = require('url'); | ||
var util = require('util'); | ||
@@ -63,3 +65,43 @@ | ||
}; | ||
http.IncomingMessage.prototype.readData = function(callback) { | ||
/** Opinionated input/form reader | ||
callback signature: function(err, Object) | ||
*/ | ||
if (this.method == 'GET') { | ||
var data = url.parse(this.url, true).query; | ||
setImmediate(function() { | ||
callback(null, data); | ||
}); | ||
} | ||
else { | ||
var content_type = this.headers['content-type'] || ''; | ||
this.readToEnd(function(err, body) { | ||
if (err) return callback(err); | ||
if (content_type.match(/application\/json/)) { | ||
// empty body translates to null | ||
if (body.length === 0) { | ||
callback(null, null); | ||
} | ||
else { | ||
try { | ||
callback(null, JSON.parse(body)); | ||
} | ||
catch (exc) { | ||
callback(exc); | ||
} | ||
} | ||
} | ||
else if (content_type.match(/application\/x-www-form-urlencoded/)) { | ||
// will querystring.parse ever throw? | ||
callback(null, querystring.parse(body.toString())); | ||
} | ||
else { | ||
callback(null, body); | ||
} | ||
}); | ||
} | ||
}; | ||
// Response | ||
@@ -66,0 +108,0 @@ http.ServerResponse.prototype.writeEnd = function(s) { |
{ | ||
"name": "http-enhanced", | ||
"version": "0.3.1", | ||
"version": "0.4.0", | ||
"main": "index.js", | ||
@@ -5,0 +5,0 @@ "description": "Drop-in replacement for Node.js standard `http` API with various helpers.", |
@@ -111,2 +111,15 @@ # http-enhanced | ||
### request.readData(callback) | ||
Wraps `req.readToEnd()` and uses the request's `Content-type` header to determine whether to parse the request as JSON or a form querystring. | ||
- **application/json**: Returns result of `JSON.parse`. Interprets empty `application/json` requests as `null`, instead of throwing (`JSON.parse('')` will raise a SyntaxError normally). | ||
- **application/x-www-form-urlencoded**: Returns result of `querystring.parse`. | ||
- otherwise, returns the same thing as `readToEnd`, a Buffer. | ||
Does not work for uploads (use something like formidable). | ||
Returns the parsed querystring for GET requests. | ||
## Response | ||
@@ -192,2 +205,2 @@ | ||
Copyright © 2013 Christopher Brown. [MIT Licensed](LICENSE). | ||
Copyright © 2013–2014 Christopher Brown. [MIT Licensed](LICENSE). |
Sorry, the diff of this file is not supported yet
12584
138
205