Skip to content

Commit

Permalink
json parser middleware, use freelist
Browse files Browse the repository at this point in the history
  • Loading branch information
chjj committed Sep 10, 2011
1 parent 574497b commit e4fe18d
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion lib/json.js
Expand Up @@ -4,7 +4,8 @@
*/

var EventEmitter = require('events').EventEmitter
, StringDecoder = require('string_decoder').StringDecoder;
, StringDecoder = require('string_decoder').StringDecoder
, FreeList = require('freelist').FreeList;

/**
* Parser
Expand Down Expand Up @@ -419,6 +420,34 @@ Parser.create = function(parser) {
module.exports = exports = Parser.create;
exports.Parser = Parser;

exports.middleware = function() {
var parsers = new FreeList('parsers', 20, function() {
return Parser.create();
});
return function(req, res, next) {
if (req._json) return next();
req._json = true;

var type = req.headers['content-type'];
if (type && type.split(';')[0].trim() === 'application/json') {
var parser = parsers.alloc();

parser.on('error', function(err) {
req.socket.destroy();
next(err);
});

parser.on('end', function(data) {
parsers.free(parser);
req.body = data;
next();
});
} else {
next();
}
};
};

/**
* Crude Test
*/
Expand Down

0 comments on commit e4fe18d

Please sign in to comment.