From 48f037a8eb388a114d8025ccb943f8b548c4c096 Mon Sep 17 00:00:00 2001 From: Longzhang Tian <15257546+longztian@users.noreply.github.com> Date: Sat, 17 Sep 2016 13:58:26 -0500 Subject: [PATCH] lazy evaluation on dynamic cookie options --- package.json | 2 +- src/session.js | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index e8ca2dc..714a4bc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "koa-session-minimal", - "version": "3.0.0", + "version": "3.0.1", "description": "Minimal implementation of session middleware for Koa 2. Inspired by and compatible with koa-generic-session", "main": "dist/session.js", "scripts": { diff --git a/src/session.js b/src/session.js index 48fcb69..58e8f50 100644 --- a/src/session.js +++ b/src/session.js @@ -20,15 +20,16 @@ const cookieOpt = (cookie) => { } const deleteSession = (ctx, key, cookie, store, sid) => { - const deleteOption = Object.assign({}, cookie) - delete deleteOption.maxAge - ctx.cookies.set(key, null, deleteOption) + const options = cookie instanceof Function ? cookieOpt(cookie(ctx)) : Object.assign({}, cookie) + delete options.maxAge + ctx.cookies.set(key, null, options) store.destroy(`${key}:${sid}`) } const saveSession = (ctx, key, cookie, store, sid) => { - const ttl = cookie.maxAge > 0 ? cookie.maxAge : ONE_DAY - ctx.cookies.set(key, sid, cookie) + const options = cookie instanceof Function ? cookieOpt(cookie(ctx)) : cookie + const ttl = options.maxAge > 0 ? options.maxAge : ONE_DAY + ctx.cookies.set(key, sid, options) store.set(`${key}:${sid}`, ctx.session, ttl) } @@ -36,7 +37,7 @@ module.exports = (options) => { const opt = options || {} const key = opt.key || 'koa:sess' const store = new Store(opt.store || new MemoryStore()) - const defaultCookie = opt.cookie instanceof Function ? opt.cookie : cookieOpt(opt.cookie) + const cookie = opt.cookie instanceof Function ? opt.cookie : cookieOpt(opt.cookie) return async (ctx, next) => { // eslint-disable-line arrow-parens // initialize session id and data @@ -64,7 +65,6 @@ module.exports = (options) => { await next() - const cookie = defaultCookie instanceof Function ? cookieOpt(defaultCookie(ctx)) : defaultCookie const sessionHasData = ctx.session && Object.keys(ctx.session).length if (sid !== cookieSid) { // a new session id