Permalink
Browse files

Added tests and implementation for middleware using the existing Expr…

…ess Array of Functions API.
  • Loading branch information...
1 parent 33ed729 commit d4b0c9c594468415037e7d85484360698c6d2709 Hunter Loftis committed Jan 3, 2012
Showing with 42 additions and 15 deletions.
  1. +21 −14 index.js
  2. +12 −1 test/fixtures/cat.js
  3. +9 −0 test/resource.test.js
View
35 index.js
@@ -140,22 +140,29 @@ Resource.prototype.map = function(method, path, fn){
, fn: fn
};
- // apply the route
- this.app[method](route, function(req, res, next){
- req.format = req.params.format || req.format || self.format;
- if (req.format) res.contentType(req.format);
- if ('object' == typeof fn) {
- if (req.format && fn[req.format]) {
- fn[req.format](req, res, next);
- } else if (fn.default) {
- fn.default(req, res, next);
+ // apply Array of middleware
+ if (fn instanceof Array) {
+ // TODO: Make arrays of middleware also work with formats
+ this.app[method](route, fn);
+ }
+ else {
+ // apply the route
+ this.app[method](route, function(req, res, next){
+ req.format = req.params.format || req.format || self.format;
+ if (req.format) res.contentType(req.format);
+ if ('object' == typeof fn) {
+ if (req.format && fn[req.format]) {
+ fn[req.format](req, res, next);
+ } else if (fn.default) {
+ fn.default(req, res, next);
+ } else {
+ res.send(406);
+ }
} else {
- res.send(406);
+ fn(req, res, next);
}
- } else {
- fn(req, res, next);
- }
- });
+ });
+ }
return this;
};
View
13 test/fixtures/cat.js
@@ -5,4 +5,15 @@ exports.index = function(req, res){
exports.new = function(req, res){
res.send('new cat');
-};
+};
+
+exports.filter = function(req, res, next) {
+ req.usertype = 'cat owner';
+ next();
+};
+
+exports.edit = [
+ exports.filter,
+ function(req, res, next) {
+ res.send('usertype: ' + req.usertype);
+ }];
View
9 test/resource.test.js
@@ -328,5 +328,14 @@ module.exports = {
assert.response(app,
{ url: '/api/cat/new' },
{ body: 'new cat' });
+ },
+
+ 'test middleware by array': function() {
+ var app = express.createServer();
+ var cat = app.resource('api/cat', require('./fixtures/cat'));
+
+ assert.response(app,
+ { url: '/api/cat/1/edit' },
+ { body: 'usertype: cat owner' });
}
};

0 comments on commit d4b0c9c

Please sign in to comment.