Skip to content

Commit

Permalink
Add next("router") to exit from router
Browse files Browse the repository at this point in the history
closes #2241
closes #2371
  • Loading branch information
blakeembrey authored and dougwilson committed Feb 26, 2017
1 parent 51f5290 commit 9722202
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions History.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ unreleased
==========

* Add debug message when loading view engine
* Add `next("router")` to exit from router
* Fix case where `router.use` skipped requests routes did not
* Remove usage of `res._headers` private field
- Improves compatibility with Node.js 8 nightly
Expand Down
6 changes: 6 additions & 0 deletions lib/router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,12 @@ proto.handle = function handle(req, res, out) {
removed = '';
}

// signal to exit router
if (layerError === 'router') {
setImmediate(done, null)
return
}

// no more matching layers
if (idx >= stack.length) {
setImmediate(done, layerError);
Expand Down
6 changes: 6 additions & 0 deletions lib/router/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,16 @@ Route.prototype.dispatch = function dispatch(req, res, done) {
next();

function next(err) {
// signal to exit route
if (err && err === 'route') {
return done();
}

// signal to exit router
if (err && err === 'router') {
return done(err)
}

var layer = stack[idx++];
if (!layer) {
return done(err);
Expand Down
31 changes: 31 additions & 0 deletions test/app.router.js
Original file line number Diff line number Diff line change
Expand Up @@ -932,6 +932,37 @@ describe('app.router', function(){
})
})

describe('when next("router") is called', function () {
it('should jump out of router', function (done) {
var app = express()
var router = express.Router()

function fn (req, res, next) {
res.set('X-Hit', '1')
next('router')
}

router.get('/foo', fn, function (req, res, next) {
res.end('failure')
})

router.get('/foo', function (req, res, next) {
res.end('failure')
})

app.use(router)

app.get('/foo', function (req, res) {
res.end('success')
})

request(app)
.get('/foo')
.expect('X-Hit', '1')
.expect(200, 'success', done)
})
})

describe('when next(err) is called', function(){
it('should break out of app.router', function(done){
var app = express()
Expand Down

0 comments on commit 9722202

Please sign in to comment.