docs: add more docs about app.context

references:

- https://github.com/koajs/koa/issues/652
master
jongleberry 2016-05-14 08:36:50 -07:00
parent 808768a597
commit e61d54565b
1 changed files with 16 additions and 2 deletions

View File

@ -184,13 +184,27 @@ ctx.cookies.set('name', 'tobi', { signed: true });
## app.context
The recommended namespace to extend with information that's useful
throughout the lifetime of your application, as opposed to a per request basis.
`app.context` is the prototype from which `ctx` is created from.
You may add additional properties to `ctx` by editing `app.context`.
This is useful for adding properties or methods to `ctx` to be used across your entire app,
which may be more performant (no middleware) and/or easier (fewer `require()`s)
at the expense of relying more on `ctx`, which could be considered an anti-pattern.
For example, to add a reference to your database from `ctx`:
```js
app.context.db = db();
app.use(async (ctx) => {
console.log(ctx.db);
});
```
Note:
- Many properties on `ctx` are defined using getters, setters, and `Object.defineProperty()`. You can only edit these properties (not recommended) by using `Object.defineProperty()` on `app.context`. See https://github.com/koajs/koa/issues/652.
- Mounted apps currently use its parent's `ctx` and settings. Thus, mounted apps are really just groups of middleware.
## Error Handling
By default outputs all errors to stderr unless `app.silent` is `true`.