From 6847fe68bdf8fb711b870f7d627c627a2c90d0e3 Mon Sep 17 00:00:00 2001 From: Matthew Mueller Date: Tue, 18 Nov 2014 00:54:14 -0800 Subject: [PATCH] added: ctx.state as the recommended namespace for passing information through middleware and routes. --- docs/api/context.md | 8 ++++++++ lib/application.js | 1 + test/context/state.js | 21 +++++++++++++++++++++ 3 files changed, 30 insertions(+) create mode 100644 test/context/state.js 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); + }) +})