koa-lite/docs/guide.md

238 lines
6.6 KiB
Markdown
Raw Normal View History

2013-09-03 01:25:17 +00:00
2013-12-19 04:09:17 +00:00
# Guide
2016-05-13 06:27:18 +00:00
This guide covers Koa topics that are not directly API related, such as best practices for writing middleware and application structure suggestions. In these examples we use async functions as middleware - you can also use 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, 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) {
const start = Date.now();
await next();
const ms = Date.now() - 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:
2018-01-31 05:05:00 +00:00
![Koa middleware](/docs/middleware.gif)
2013-09-03 02:05:49 +00:00
2017-09-26 04:22:22 +00:00
1. Create a date to track response time
2. Await control to the next middleware
2017-09-26 04:22:22 +00:00
3. Create another date to track duration
4. Await control to the next middleware
2017-09-26 04:22:22 +00:00
5. Set the response body to "Hello World"
6. Calculate duration time
7. Output log line
8. Calculate response time
9. Set `X-Response-Time` header field
10. Hand off to Koa to handle the response
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) {
2016-06-22 03:01:51 +00:00
if ('/random' == ctx.path) {
2016-03-15 15:35:52 +00:00
ctx.body = Math.floor(Math.random() * 10);
} else {
await next();
}
};
async function backwards(ctx, next) {
2016-06-22 03:01:51 +00:00
if ('/backwards' == ctx.path) {
ctx.body = 'sdrawkcab';
} else {
await next();
}
}
async function pi(ctx, next) {
2016-06-22 03:01:51 +00:00
if ('/pi' == ctx.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
2018-01-31 05:05:00 +00:00
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.
2013-11-27 05:37:22 +00:00
```
$ 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
```