From 26f0d16644652c1ef385311e4f0d9aa92523d272 Mon Sep 17 00:00:00 2001 From: Jonathan Ong Date: Mon, 30 Dec 2013 22:20:32 -0800 Subject: [PATCH] docs: cleanup middleware guide, including TJ's yoda-style conditionals changes on top of 789c30f9266758ae691d32be5bd87e23b1bca4e0. closes #158, closes #157 --- docs/guide.md | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/docs/guide.md b/docs/guide.md index b5621b0..0c443a5 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -118,15 +118,13 @@ function logger(format){ } ``` -### Adding multiple middleware at once +### Combining multiple middleware - To add multiple middleware at once chain them together with - [.call()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) - and then return another function that yields the chain. + Sometimes you want to "compose" multiple middleware into a single middleware for easy re-use or exporting. To do so, you may chain them together with `.call(this, next)`s, then return another function that yields the chain. ```js function *random(next){ - if (this.path == '/random') { + if ('/random' == this.path) { this.body = Math.floor(Math.random()*10); } else { yield next; @@ -134,7 +132,7 @@ function *random(next){ }; function *backwords(next) { - if (this.path == '/backwords') { + if ('/backwords' == this.path) { this.body = 'sdrowkcab'; } else { yield next; @@ -142,18 +140,22 @@ function *backwords(next) { } function *pi(next){ - if (this.path == '/pi') { + if ('/pi' == this.path) { this.body = String(Math.PI); } else { yield next; } } -app.use(function*(next){ +function *all(next) { yield random.call(this, backwords.call(this, pi.call(this, next))); -}); +} + +app.use(all); ``` + This is exactly what [koa-compose](https://github.com/koajs/compose) does, which Koa internally uses to create and dispatch the middleware stack. + ### Response Middleware Middleware that decide to respond to a request and wish to bypass downstream middleware may