koa-lite/docs/guide.md

257 lines
7.3 KiB
Markdown
Raw Permalink Normal View History

2013-09-03 01:25:17 +00:00
2013-12-19 04:09:17 +00:00
# Guide
This guide covers Koa topics that are not directly API related, such as best practices for writing middleware, application structure suggestions, here we use async function as middleware you can also you commonFunction or generatorFunction which will be a little different.
2013-12-19 04:09:17 +00:00
2013-09-03 01:25:17 +00:00
## Writing Middleware
Koa middleware are simple functions which return a `MiddlewareFunction` with signature (ctx, next). When
the middleware is run by an "upstream" middleware, it must manually invoke `next()` to run the "downstream" middleware.
2013-09-03 01:25:17 +00:00
For example if you wanted to track how long it takes for a request to propagate through Koa by adding an
`X-Response-Time` header field the middleware would look like the following:
```js
async function responseTime(ctx, next) {
2016-03-15 15:35:52 +00:00
const start = new Date();
await next();
2016-03-15 15:35:52 +00:00
const ms = new Date() - start;
ctx.set('X-Response-Time', `${ms}ms`);
2013-09-03 01:25:17 +00:00
}
app.use(responseTime);
```
If you're a front-end developer you can think any code before `next();` as the "capture" phase,
while any code after is the "bubble" phase. This crude gif illustrates how async function allow us
2013-09-03 02:05:49 +00:00
to properly utilize stack flow to implement request and response flows:
2014-08-03 16:37:49 +00:00
![koa middleware](/docs/middleware.gif)
2013-09-03 02:05:49 +00:00
2013-09-03 02:17:49 +00:00
1. Create a date to track duration
2. Await control to the next middleware
2013-09-03 02:17:49 +00:00
3. Create another date to track response time
4. Await control to the next middleware
5. Await immediately since `contentLength` only works with responses
6. Await upstream to Koa's noop middleware
2013-09-03 02:17:49 +00:00
7. Ignore setting the body unless the path is "/"
8. Set the response to "Hello World"
2013-09-03 02:18:48 +00:00
9. Ignore setting `Content-Length` when no body is present
2013-09-03 02:17:49 +00:00
10. Set the field
11. Output log line
12. Set `X-Response-Time` header field before response
13. Hand off to Koa to handle the response
2013-09-03 02:13:47 +00:00
2013-09-03 02:18:10 +00:00
Note that the final middleware (step __6__) await to what looks to be nothing - it's actually
yielding to a no-op promise within Koa. This is so that every middleware can conform with the
same API, and may be placed before or after others. If you removed `next();` from the furthest
"downstream" middleware everything would function appropriately, however it would no longer conform
2013-09-03 02:18:37 +00:00
to this behaviour.
2013-09-03 02:17:29 +00:00
For example this would be fine:
```js
2016-03-15 15:35:52 +00:00
app.use(async function response(ctx, next) {
if ('/' != this.url) return;
ctx.body = 'Hello World';
2013-09-03 02:17:29 +00:00
});
```
Next we'll look at the best practices for creating Koa middleware.
2013-09-03 01:25:17 +00:00
## Middleware Best Practices
2013-09-03 01:27:47 +00:00
This section covers middleware authoring best practices, such as middleware
accepting options, named middleware for debugging, among others.
### Middleware options
2013-09-03 01:25:17 +00:00
When creating public middleware it's useful to conform to the convention of
wrapping the middleware in a function that accepts options, allowing users to
extend functionality. Even if your middleware accepts _no_ options, this is still
a good idea to keep things uniform.
Here our contrived `logger` middleware accepts a `format` string for customization,
and returns the middleware itself:
```js
2014-03-24 18:21:15 +00:00
function logger(format) {
2013-09-03 01:25:17 +00:00
format = format || ':method ":url"';
2016-03-15 15:35:52 +00:00
return async function (ctx, next) {
2015-10-24 09:21:47 +00:00
const str = format
.replace(':method', ctx.method)
.replace(':url', ctx.url);
2013-09-03 01:25:17 +00:00
console.log(str);
2013-11-27 05:37:22 +00:00
await next();
2016-03-15 15:35:52 +00:00
};
2013-09-03 01:25:17 +00:00
}
app.use(logger());
app.use(logger(':method :url'));
```
2013-09-03 01:27:47 +00:00
### Named middleware
2013-11-27 05:37:22 +00:00
Naming middleware is optional, however it's useful for debugging purposes to assign a name.
2013-09-03 01:27:47 +00:00
```js
2014-03-24 18:21:15 +00:00
function logger(format) {
2016-03-15 15:35:52 +00:00
return async function logger(ctx, next) {
2016-03-15 15:35:52 +00:00
};
2013-09-03 01:27:47 +00:00
}
```
### Combining multiple middleware with koa-compose
Sometimes you want to "compose" multiple middleware into a single middleware for easy re-use or exporting. You can use [koa-compose](https://github.com/koajs/compose)
```js
const compose = require('koa-compose');
async function random(ctx, next) {
if ('/random' == this.path) {
2016-03-15 15:35:52 +00:00
ctx.body = Math.floor(Math.random() * 10);
} else {
await next();
}
};
async function backwards(ctx, next) {
if ('/backwards' == this.path) {
ctx.body = 'sdrawkcab';
} else {
await next();
}
}
async function pi(ctx, next) {
if ('/pi' == this.path) {
ctx.body = String(Math.PI);
} else {
await next();
}
}
2016-03-15 15:35:52 +00:00
const all = compose([random, backwards, pi]);
app.use(all);
```
### Response Middleware
Middleware that decide to respond to a request and wish to bypass downstream middleware may
simply omit `next()`. Typically this will be in routing middleware, but this can be performed by
any. For example the following will respond with "two", however all three are executed, giving the
downstream "three" middleware a chance to manipulate the response.
```js
2016-03-15 15:35:52 +00:00
app.use(async function (ctx, next) {
console.log('>> one');
await next();
2016-03-15 15:35:52 +00:00
console.log('<< one');
});
2016-03-15 15:35:52 +00:00
app.use(async function (ctx, next) {
console.log('>> two');
ctx.body = 'two';
await next();
console.log('<< two');
});
2016-03-15 15:35:52 +00:00
app.use(async function (ctx, next) {
console.log('>> three');
await next();
console.log('<< three');
});
```
The following configuration omits `next()` in the second middleware, and will still respond
with "two", however the third (and any other downstream middleware) will be ignored:
```js
2016-03-15 15:35:52 +00:00
app.use(async function (ctx, next) {
console.log('>> one');
await next();
2016-03-15 15:35:52 +00:00
console.log('<< one');
});
2016-03-15 15:35:52 +00:00
app.use(async function (ctx, next) {
console.log('>> two');
ctx.body = 'two';
console.log('<< two');
});
2016-03-15 15:35:52 +00:00
app.use(async function (ctx, next) {
console.log('>> three');
await next();
console.log('<< three');
});
```
When the furthest downstream middleware executes `next();`, it's really yielding to a noop
2013-11-28 04:52:36 +00:00
function, allowing the middleware to compose correctly anywhere in the stack.
2013-09-03 02:31:11 +00:00
## Async operations
2013-09-03 01:25:17 +00:00
Async function and promise forms Koa's foundation, allowing
2013-09-03 02:31:11 +00:00
you to write non-blocking sequential code. For example this middleware reads the filenames from `./docs`,
and then reads the contents of each markdown file in parallel before assigning the body to the joint result.
```js
const fs = require('fs-promise');
2013-09-03 02:31:11 +00:00
2016-03-15 15:35:52 +00:00
app.use(async function (ctx, next) {
const paths = await fs.readdir('docs');
const files = await Promise.all(paths.map(path => fs.readFile(`docs/${path}`, 'utf8')));
2013-09-03 02:31:11 +00:00
ctx.type = 'markdown';
ctx.body = files.join('');
2013-09-03 02:31:11 +00:00
});
```
2013-09-03 01:25:17 +00:00
2013-11-27 05:37:22 +00:00
## Debugging Koa
Koa along with many of the libraries it's built with support the __DEBUG__ environment variable from [debug](https://github.com/visionmedia/debug) which provides simple conditional logging.
For example
to see all koa-specific debugging information just pass `DEBUG=koa*` and upon boot you'll see the list of middleware used, among other things.
```
$ DEBUG=koa* node --harmony examples/simple
koa:application use responseTime +0ms
koa:application use logger +4ms
koa:application use contentLength +0ms
koa:application use notfound +0ms
koa:application use response +0ms
koa:application listen +0ms
```
2013-12-30 06:16:04 +00:00
Since JavaScript does not allow defining function names at
runtime, you can also set a middleware's name as `._name`.
This useful when you don't have control of a middleware's name.
For example:
```js
2015-10-24 09:21:47 +00:00
const path = require('path');
2016-03-15 15:35:52 +00:00
const serve = require('koa-static');
2013-12-30 06:16:04 +00:00
2016-03-15 15:35:52 +00:00
const publicFiles = serve(path.join(__dirname, 'public'));
2013-12-30 06:16:04 +00:00
publicFiles._name = 'static /public';
app.use(publicFiles);
```
2016-03-15 15:35:52 +00:00
Now, instead of just seeing "serve" when debugging, you will see:
2013-12-30 06:16:04 +00:00
```
koa:application use static /public +0ms
```