From 728917164cc00dd02382560f52c6f78936adb4c3 Mon Sep 17 00:00:00 2001 From: Douglas Christopher Wilson Date: Wed, 17 Sep 2014 12:37:56 -0700 Subject: [PATCH] Fix router.use to accept array of middleware without path --- History.md | 1 + lib/router/index.js | 14 ++++++++++++-- test/Router.js | 22 ++++++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/History.md b/History.md index 1e9e7d3796..42b9166c5e 100644 --- a/History.md +++ b/History.md @@ -2,6 +2,7 @@ unreleased ========== * Fix regression for empty string `path` in `app.use` + * Fix `router.use` to accept array of middleware without path * Improve error message for bad `app.use` arguments 4.9.1 / 2014-09-16 diff --git a/lib/router/index.js b/lib/router/index.js index 8bdce9197c..64fcd1e3ac 100644 --- a/lib/router/index.js +++ b/lib/router/index.js @@ -412,9 +412,19 @@ proto.use = function use(fn) { var self = this; // default path to '/' + // disambiguate router.use([fn]) if (typeof fn !== 'function') { - offset = 1; - path = fn; + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } } var callbacks = utils.flatten(slice.call(arguments, offset)); diff --git a/test/Router.js b/test/Router.js index 9085acd7f0..85a5331207 100644 --- a/test/Router.js +++ b/test/Router.js @@ -310,6 +310,28 @@ describe('Router', function(){ router.use.bind(router, '/', null).should.throw(/requires middleware function.*Null/) router.use.bind(router, '/', new Date()).should.throw(/requires middleware function.*Date/) }) + + it('should accept array of middleware', function(done){ + var count = 0; + var router = new Router(); + + function fn1(req, res, next){ + assert.equal(++count, 1); + next(); + } + + function fn2(req, res, next){ + assert.equal(++count, 2); + next(); + } + + router.use([fn1, fn2], function(req, res){ + assert.equal(++count, 3); + done(); + }); + + router.handle({ url: '/foo', method: 'GET' }, {}, function(){}); + }) }) describe('.param', function() {