diff --git a/docs/api/context.md b/docs/api/context.md index a270f5e..390c862 100644 --- a/docs/api/context.md +++ b/docs/api/context.md @@ -50,6 +50,14 @@ app.use(function *(){ A koa `Response` object. +### ctx.state + + The recommended namespace for passing information through middleware and to your frontend views. + +```js +this.state.user = yield User.find(id); +``` + ### ctx.app Application instance reference. diff --git a/lib/application.js b/lib/application.js index 1b1766d..fa8858f 100644 --- a/lib/application.js +++ b/lib/application.js @@ -146,6 +146,7 @@ app.createContext = function(req, res){ context.originalUrl = request.originalUrl = req.url; context.cookies = new Cookies(req, res, this.keys); context.accept = request.accept = accepts(req); + context.state = {}; return context; }; diff --git a/test/context/state.js b/test/context/state.js new file mode 100644 index 0000000..78eb02c --- /dev/null +++ b/test/context/state.js @@ -0,0 +1,21 @@ + +var request = require('supertest'); +var assert = require('assert'); +var koa = require('../..'); + +describe('ctx.state', function() { + it('should provide a ctx.state namespace', function(done) { + var app = koa(); + + app.use(function *() { + assert.deepEqual(this.state, {}); + }); + + var server = app.listen(); + + request(server) + .get('/') + .expect(404) + .end(done); + }) +})