testling - automated browser tests
browserling - interactive browser testing
commit 877197b629b602b05d5982e83afe809761016dfe
Author: James Halliday
Date: Sat Jan 29 18:14:55 2011 +0000

I thought http sessions in node.js were a bit cumbersome so I hacked up sesame to make it crazy simple: just update req.session!

Using harmony proxies, this req.session interface even works with a database store so your sessions persist across restarts and crashes!

Here's a simple example that increments a counter, times.

var connect = require('connect');
var webserver = connect.createServer();
webserver.use(require('sesame')());

webserver.use(connect.router(function (app) {
    app.get('/', function (req, res) {
        req.session.times = (req.session.times || 0) + 1;

        res.writeHead(200, { 'Content-Type' : 'text/plain' });
        res.end(req.session.times + ' times!');
    });
}));

console.log('Listening on 9090');
webserver.listen(9090);

With no arguments, require('sesame')() just loads up sessions in-memory with no disk backup. You can pass in a storage engine like nStore and supermarket to save the sessions to disk:

var connect = require('connect');
var webserver = connect.createServer();
webserver.use(require('sesame')(<b>{
    store : new(require('supermarket'))({
        filename : __dirname + '/supermarket.db', json : true,
    })
}</b>));

webserver.use(connect.router(function (app) {
    app.get('/', function (req, res) {
        req.session.times = (req.session.times || 0) + 1;

        res.writeHead(200, { 'Content-Type' : 'text/plain' });
        res.end(req.session.times + ' times!');
    });
}));

console.log('Listening on 9090');
webserver.listen(9090);

And now the req.session.times state persists across server restarts! Thanks to some harmony proxy hacks on the backend, the interface doesn't change at all! You can update deeply nested values too:

var connect = require('connect');
var webserver = connect.createServer();
webserver.use(require('sesame')({
    store : new(require('supermarket'))({
        filename : __dirname + '/supermarket.db', json : true,
    })
}));

webserver.use(connect.router(function (app) {
    app.get('/', function (req, res) {
        req.session.times = (req.session.times || 0) + 1;
        <b>if (!req.session.foo) {
            req.session.foo = { bar : { baz : 1 } };
        }
        req.session.foo.bar.baz *= 2;</b>

        res.writeHead(200, { 'Content-Type' : 'text/plain' });
        res.end(
            req.session.times + ' times!'
            <b>+ ' baz = ' + req.session.foo.bar.baz</b>
        );
    });
}));

console.log('Listening on 9090');
webserver.listen(9090);

And it all just works™. Plus, the writes are buffered with a process.nextTick() so if you update a bunch of elements in req.session one after the other sesame will only do one write for all of them.

sesame on github

Open sesame!

more
git clone http://substack.net/blog.git