update guide docs for new middleware style

This commit is contained in:
TJ Holowaychuk 2013-11-10 15:40:59 -07:00
parent ee6dce83af
commit 9ee6ada2d5

View file

@ -8,13 +8,11 @@
`X-Response-Time` header field the middleware would look like the following: `X-Response-Time` header field the middleware would look like the following:
```js ```js
function responseTime(next){ function *responseTime(next){
return function *(){ var start = new Date;
var start = new Date; yield next;
yield next; var ms = new Date - start;
var ms = new Date - start; this.set('X-Response-Time', ms + 'ms');
this.set('X-Response-Time', ms + 'ms');
}
} }
app.use(responseTime); app.use(responseTime);
@ -23,13 +21,11 @@ app.use(responseTime);
Here's another way to write the same thing, inline: Here's another way to write the same thing, inline:
```js ```js
app.use(function(next){ app.use(function *(next){
return function *(){ var start = new Date;
var start = new Date; yield next;
yield next; var ms = new Date - start;
var ms = new Date - start; this.set('X-Response-Time', ms + 'ms');
this.set('X-Response-Time', ms + 'ms');
}
}); });
``` ```
@ -63,19 +59,8 @@ to this behaviour.
For example this would be fine: For example this would be fine:
```js ```js
app.use(function(){ app.use(function *response(){
return function *response(){ if ('/' != this.url) return;
if ('/' != this.url) return;
this.body = 'Hello World';
}
});
```
It's important to note that not all middleware will need to conform, the best example of this
is a router, which are typically always acting as end-points, or downstream middleware:
````js
app.use(get('/', function *(){
this.body = 'Hello World'; this.body = 'Hello World';
}); });
``` ```
@ -101,16 +86,14 @@ app.use(get('/', function *(){
function logger(format){ function logger(format){
format = format || ':method ":url"'; format = format || ':method ":url"';
return function(next){ return function *(next){
return function *(){ var str = format
var str = format .replace(':method', this.method)
.replace(':method', this.method) .replace(':url', this.url);
.replace(':url', this.url);
console.log(str); console.log(str);
yield next; yield next;
}
} }
} }
@ -125,10 +108,8 @@ app.use(logger(':method :url'));
```js ```js
function logger(format){ function logger(format){
return function(next){ return function *logger(next){
return function *logger(){
// ^-- name this guy
}
} }
} }
``` ```
@ -143,17 +124,15 @@ function logger(format){
```js ```js
var fs = require('co-fs'); var fs = require('co-fs');
app.use(function(){ app.use(function *(){
return function *(){ var paths = yield fs.readdir('docs');
var paths = yield fs.readdir('docs');
var files = yield paths.map(function(path){ var files = yield paths.map(function(path){
return fs.readFile('docs/' + path, 'utf8'); return fs.readFile('docs/' + path, 'utf8');
}); });
this.type = 'markdown'; this.type = 'markdown';
this.body = files.join(''); this.body = files.join('');
}
}); });
``` ```