From e61d54565b6bfe1810ea41afa702db8f9c06691a Mon Sep 17 00:00:00 2001 From: jongleberry Date: Sat, 14 May 2016 08:36:50 -0700 Subject: [PATCH] docs: add more docs about app.context references: - https://github.com/koajs/koa/issues/652 --- docs/api/index.md | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/docs/api/index.md b/docs/api/index.md index e20350f..65c52c7 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -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`.