diff --git a/index.js b/index.js index b095060..62aabce 100644 --- a/index.js +++ b/index.js @@ -2,7 +2,6 @@ const debug = require('debug')('koa-session'); const ContextSession = require('./lib/context'); -const util = require('./lib/util'); const assert = require('assert'); const uid = require('uid-safe'); const is = require('is-type-of'); @@ -70,14 +69,6 @@ function formatOpts(opts) { debug('session options %j', opts); - // setup encoding/decoding - if (typeof opts.encode !== 'function') { - opts.encode = util.encode; - } - if (typeof opts.decode !== 'function') { - opts.decode = util.decode; - } - const store = opts.store; if (store) { assert(is.function(store.get), 'store.get must be function'); diff --git a/lib/context.js b/lib/context.js index f1dc702..8aed0ae 100644 --- a/lib/context.js +++ b/lib/context.js @@ -69,10 +69,20 @@ class ContextSession { const ctx = this.ctx; const opts = this.opts; - const externalKey = ctx.cookies.get(opts.key, opts); - debug('get external key from cookie %s', externalKey); + const cookie = ctx.cookies.get(opts.key, opts); + debug('get external key from cookie %s', cookie); - if (!externalKey) { + if (!cookie) { + // create a new `externalKey` + this.create(); + return; + } + let externalKey = cookie; + try { + if (typeof opts.decode === 'function') { + externalKey = opts.decode(externalKey); + } + } catch (err) { // create a new `externalKey` this.create(); return; @@ -109,7 +119,7 @@ class ContextSession { let json; debug('parse %s', cookie); try { - json = opts.decode(cookie); + json = typeof opts.decode === 'function' ? opts.decode(cookie) : util.decode(cookie); } catch (err) { // backwards compatibility: // create a new session if parsing fails. @@ -263,13 +273,17 @@ class ContextSession { changed, rolling: opts.rolling, }); - this.ctx.cookies.set(key, externalKey, opts); + let cookie = externalKey; + if (typeof opts.encode === 'function') { + cookie = opts.encode(externalKey); + } + this.ctx.cookies.set(key, cookie, opts); return; } // save to cookie debug('save %j to cookie', json); - json = opts.encode(json); + json = typeof opts.encode === 'function' ? opts.encode(json) : util.encode(json); debug('save %s', json); this.ctx.cookies.set(key, json, opts); diff --git a/test/cookie.test.js b/test/cookie.test.js index dc15fb9..ddc2462 100644 --- a/test/cookie.test.js +++ b/test/cookie.test.js @@ -761,10 +761,10 @@ describe('Koa Session Cookie', () => { before(() => { app = App({ rolling: true }); - app.use(function* () { - console.log(this.path); - if (this.path === '/set') this.session = { foo: 'bar' }; - this.body = this.session; + app.use(async function(ctx) { + console.log(ctx.path); + if (ctx.path === '/set') ctx.session = { foo: 'bar' }; + ctx.body = ctx.session; }); });