Skip to content

Commit

Permalink
move parseJson to its own file
Browse files Browse the repository at this point in the history
Moves parseJson middleware to its own file. This requires moving the join helper function that is used by parseJson and parseForm to a seperate file as well. This new file is forEachable.js and is to hold utility functions for working with forEachables.
  • Loading branch information
Nathan committed Jun 19, 2013
1 parent 50a3157 commit 0a87796
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 30 deletions.
13 changes: 13 additions & 0 deletions lib/forEachable.js
@@ -0,0 +1,13 @@
var q = require('./q');

exports.join = function (forEachable) {
var body = '';

function appendChunk(chunk) {
body += chunk;
};

return q.when(forEachable.forEach(appendChunk), function () {
return body;
});
};
32 changes: 2 additions & 30 deletions lib/middleware.js
Expand Up @@ -19,42 +19,14 @@ var middleware = function (handler) {

module.exports = middleware;

function join(forEachable) {
var body = '',
appendChunk;

appendChunk = function(chunk) {
body += chunk;
};

return when(forEachable.forEach(appendChunk), function success() {
return body;
});
}

function deprecate(oldName, newName, fn) {
return function () {
console.log(oldName + ' is deprecated, please use ' + newName + ' instead');
return fn.apply(middleware, Array.prototype.slice.call(arguments));
}
}

middleware.parseJson = middleware(function (req, nextApp) {
var contentType = req.headers['content-type'];

if (contentType && req.body) {
if (contentType === "application/json") {

return when(join(req.body), function success(body) {
req.body = JSON.parse(body);

return nextApp(req);
});
}
}

return nextApp(req);
});
middleware.parseJson = require('./middleware/parseJson');

middleware.ParseJson = deprecate('ParseJson', 'parseJson', middleware.parseJson);

Expand All @@ -69,7 +41,7 @@ middleware.parseForm = middleware.ParseForm = function(nextApp) {

if (contentType === 'application/x-www-form-urlencoded' && req.body) {

return when(join(req.body), function(body) {
return when(require('./forEachable').join(req.body), function(body) {
req.body = require('querystring').parse(body);

return nextApp(req);
Expand Down
20 changes: 20 additions & 0 deletions lib/middleware/parseJson.js
@@ -0,0 +1,20 @@
var middleware = require('../middleware')
, forEachable = require('../forEachable')
, q = require('../q');

module.exports = middleware(function (req, nextApp) {
var contentType = req.headers['content-type'];

if (contentType && req.body) {
if (contentType === 'application/json') {

return q.when(forEachable.join(req.body), function success(body) {
req.body = JSON.parse(body);

return nextApp(req);
});
}
}

return nextApp(req);
});

0 comments on commit 0a87796

Please sign in to comment.