Skip to content

Commit

Permalink
better middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
chjj committed Jul 20, 2011
1 parent df0e6f3 commit c3ee56d
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions lib/parted.js
Expand Up @@ -40,6 +40,7 @@ var parted = function(type, opt) {

this.state = 'START';
this.pending = 0;
this.written = 0;
this.last = new Buffer([0, 0, 0]);
this.buff = new Buffer(200);

Expand All @@ -59,6 +60,7 @@ parted.prototype.write = function(data) {

try {
this._parse(data);
this.written += data.length;
} catch(e) {
this._error(e);
}
Expand Down Expand Up @@ -276,30 +278,43 @@ parted.prototype._finish = function() {
}
};

// directory for uploads
/**
* Uploads
*/

parted.root = '/tmp';

/**
* Middleware
*/

parted.middleware = function(opt) {
opt = opt || {};
opt.limit = opt.limit || Infinity;
return function(req, res, next) {
if (req.body) return next();
if (req.method === 'GET'
|| req.method === 'HEAD'
|| req.body) return next();

var parts = req.body = {}
, type = req.headers['content-type'];
var type = req.headers['content-type'];

if (type && type.indexOf('multipart/form-data') === 0) {
var parser = new parted(type, opt)
, parts = req.body = {};

if (type && ~type.indexOf('multipart/form-data')) {
var parser = new parted(type, opt);
parser.on('error', function(err) {
req.destroy();
next(err);
});
parser.on('data', function(part) {
parts[part.field] = part.file || part.text;
if (parser.written > opt.limit) {
parser.emit('error', new Error('Overflow.'));
}
});
parser.on('end', next);

req.body = parts;
req.pipe(parser);
} else {
next();
Expand All @@ -325,4 +340,8 @@ var grab = function(str, name) {
}
};

/**
* Expose
*/

module.exports = parted;

0 comments on commit c3ee56d

Please sign in to comment.