docs: add more docs about app.context
references: - https://github.com/koajs/koa/issues/652
This commit is contained in:
parent
808768a597
commit
e61d54565b
1 changed files with 16 additions and 2 deletions
|
@ -184,13 +184,27 @@ ctx.cookies.set('name', 'tobi', { signed: true });
|
||||||
|
|
||||||
## app.context
|
## app.context
|
||||||
|
|
||||||
The recommended namespace to extend with information that's useful
|
`app.context` is the prototype from which `ctx` is created from.
|
||||||
throughout the lifetime of your application, as opposed to a per request basis.
|
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
|
```js
|
||||||
app.context.db = db();
|
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
|
## Error Handling
|
||||||
|
|
||||||
By default outputs all errors to stderr unless `app.silent` is `true`.
|
By default outputs all errors to stderr unless `app.silent` is `true`.
|
||||||
|
|
Loading…
Reference in a new issue