From 39715dc9a56a5f49505427ca0648f27cb941e173 Mon Sep 17 00:00:00 2001 From: "songsong.zhang" <1733458402@qq.com> Date: Thu, 16 May 2019 10:15:16 +0800 Subject: [PATCH 1/2] feat: add the parameter "ctx" to the function "genid" so can get the session id --- lib/context.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/context.js b/lib/context.js index 410996b..b9d444b 100644 --- a/lib/context.js +++ b/lib/context.js @@ -202,7 +202,7 @@ class ContextSession { create(val, externalKey) { debug('create session with val: %j externalKey: %s', val, externalKey); - if (this.store) this.externalKey = externalKey || this.opts.genid(); + if (this.store) this.externalKey = externalKey || this.opts.genid && this.opts.genid(this.ctx); this.session = new Session(this, val); } From c9e274c4c5eccdb779864c684264c9b31cccfad7 Mon Sep 17 00:00:00 2001 From: "songsong.zhang" <1733458402@qq.com> Date: Thu, 16 May 2019 17:20:25 +0800 Subject: [PATCH 2/2] feat: genid ctx test --- test/contextstore.test.js | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/test/contextstore.test.js b/test/contextstore.test.js index 1d3058e..57cfb44 100644 --- a/test/contextstore.test.js +++ b/test/contextstore.test.js @@ -96,6 +96,26 @@ describe('Koa Session External Context Store', () => { }); }); + it('should pass sid to middleware', done => { + const app = App(); + + app.use(async function(ctx) { + ctx.session.message = 'hello'; + ctx.state.sid.indexOf('_suffix').should.greaterThan(1); + ctx.body = ''; + }); + + request(app.listen()) + .get('/') + .expect('Set-Cookie', /koa:sess/) + .expect(200, (err, res) => { + if (err) return done(err); + cookie = res.header['set-cookie'].join(';'); + cookie.indexOf('_suffix').should.greaterThan(1); + done(); + }); + }); + it('should not Set-Cookie', done => { const app = App(); @@ -726,8 +746,10 @@ function App(options) { app.keys = [ 'a', 'b' ]; options = options || {}; options.ContextStore = ContextStore; - options.genid = () => { - return Date.now() + '_suffix'; + options.genid = ctx => { + const sid = Date.now() + '_suffix'; + ctx.state.sid = sid; + return sid; }; app.use(session(options, app)); return app;