Nate Starner
Nate Starner

Reputation: 521

how can I add an event listener to a session (redis) with nodejs and express?

I would like to run a function whenever a user's session is destroyed/times out. Is there a way to do with in nodejs with express using a redis session store?

Upvotes: 3

Views: 2354

Answers (1)

user254766
user254766

Reputation:

The session store's themselves inherit from EventEmitter:

https://github.com/senchalabs/connect/blob/master/lib/middleware/session/store.js

Although none of the implementations emit events for you to bind to, including the redis store:

https://github.com/visionmedia/connect-redis/blob/master/lib/connect-redis.js

You could quite easily fork connect-redis and hack these events in yourself so that you may bind to them where you need to....

RedisStore.prototype.destroy = function(sid, fn){
    sid = this.prefix + sid;
    this.client.del(sid, fn);
  };

becomes

RedisStore.prototype.destroy = function(sid, fn){
    sid = this.prefix + sid;
    this.client.del(sid, fn);
    this.emit('destroy');
  };

Then you may bind to the "destroy" event...

var connect = require('connect')
      , RedisStore = require('connect-redis')(connect);

var store = new RedisStore;

store.on('destroy', function() {
  // session was destroyed
});

connect.createServer(
  connect.cookieParser(),
  connect.session({ store: store, secret: 'keyboard cat' })
);

Upvotes: 8

Related Questions