Atomic sessions for Koa.
- Currently uses MongoDB.
- Atomic updates - don't butcher the entire session.
- Don't grab the session from the database unless necessary.
- Better error handling.
- Includes CSRF token handling
// create the app
var app = koa()
// attach the session to the app
var MongoDBSession = require('koa-atomic-session')(app, {
maxAge: '1 month'
})
// asynchronously attach the collection
// you should not start the app until you do this
require('mongodb').MongoClient.connect('mongodb://localhost', function (err, db) {
if (err) throw err
// set the collection
MongoDBSession.collection = db.collection('sessions')
// ensure indexes every time!
MongoDBSession.ensureIndex()
})
// use it in your app
app.use(function* (next) {
var session = yield this.session()
yield session.unset('user_id')
yield session.set('user_id', new ObjectID()).then(session.update)
})
Options:
key
- cookie keymaxAge
- default to 14 days
Grab the session from the database asynchronously.
Updates the new expires
time.
Change properties of the session. See database-specific options below.
Updates all the properties of the session
object after running a command.
Should always be added to a .then()
.
yield session.set('message', 'hello')
.then(session.update)
assert.equal(session.message, 'hello')
Destroys the session without creating a new one.
Creates a brand new session.
Create a CSRF token.
Assert that a CSRF token is valid.
Adds indexes on the expires
property so that expires are automatically set.
Set the collection asynchronously. You should set this collection before starting your app.
Supports most MongoDB properties. This uses mongodb-next internally. Some commands that are supported are:
- `.set(key, value)``
.unset(key)
.rename(name, newName)
.pull()
.addToSet()