koajs / generic-session

koa session store with memory, redis or others.
MIT License
414 stars 65 forks source link

If ctx.throw is called, the function `refreshSession` is never reached, and session is not saved #94

Closed niftylettuce closed 8 years ago

niftylettuce commented 8 years ago

https://github.com/koajs/generic-session/blob/f042b55429b3c0ff06588143d4984c3dc82e6cf7/lib/session.js#L338-L339

niftylettuce commented 8 years ago

Related #93 #80

niftylettuce commented 8 years ago

I figured out how to resolve this. If you want to manually save the session and cookies, or (as in my case) if you want to manually save the session and cookies in a custom error handler that overrides app.context.onerror (in koa@v2), you need to use co.wrap to wrap the save functionality of ctx.sessionStore.set (and also save the cookie with ctx.cookies.set(...). I really think that we should expose the saveNow method along with the sessionIdStore.set methods. Perhaps this can go into the refactor as described in #90.

niftylettuce commented 8 years ago

Here's a code snippet that I use in my error handler in Glazed.io based on the above logic:

        this.flash('error', err.message);
        await co.wrap(this.sessionStore.set).call(this.sessionStore, this.sessionId, this.session);
        this.cookies.set(
          config.cookiesKey,
          this.sessionId,
          this.session.cookie
        );
niftylettuce commented 8 years ago

Note that the beforeHook stuff is not called as I do not use sessionIdStore. But this a little way to get around this issue for now.

niftylettuce commented 8 years ago

thanks @dead-horse