Skip to content

Commit

Permalink
lazy evaluation on dynamic cookie options
Browse files Browse the repository at this point in the history
  • Loading branch information
lzztt committed Sep 17, 2016
1 parent bccb59a commit 48f037a
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down
14 changes: 7 additions & 7 deletions src/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,24 @@ 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)
}

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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 48f037a

Please sign in to comment.