Permalink
Browse files

Added session `Store#load(sess, fn)` to fetch a `Session` instance

  • Loading branch information...
1 parent 4123b0d commit 4e2feea325641e3271249ea811d0759223b0c345 @tj tj committed Sep 5, 2011
Showing with 64 additions and 5 deletions.
  1. +24 −3 lib/middleware/session/store.js
  2. +40 −2 test/session.test.js
@@ -39,6 +39,26 @@ Store.prototype.regenerate = function(req, fn){
};
/**
+ * Load a `Session` instance via the given `sid`
+ * and invoke the callback `fn(err, sess)`.
+ *
+ * @param {String} sid
+ * @param {Function} fn
+ * @api public
+ */
+
+Store.prototype.load = function(sid, fn){
+ var self = this;
+ this.get(sid, function(err, sess){
+ if (err) return fn(err);
+ if (!sess) return fn();
+ var req = { sessionID: sid, sessionStore: self };
+ sess = self.createSession(req, sess, false);
+ fn(null, sess);
+ });
+};
+
+/**
* Create session from JSON `sess` data.
*
* @param {IncomingRequest} req
@@ -47,13 +67,14 @@ Store.prototype.regenerate = function(req, fn){
* @api private
*/
-Store.prototype.createSession = function(req, sess){
+Store.prototype.createSession = function(req, sess, update){
var expires = sess.cookie.expires
- , orig = sess.cookie.originalMaxAge;
+ , orig = sess.cookie.originalMaxAge
+ , update = null == update ? true : false;
sess.cookie = new Cookie(sess.cookie);
if ('string' == typeof expires) sess.cookie.expires = new Date(expires);
sess.cookie.originalMaxAge = orig;
req.session = new Session(req, sess);
- req.session.resetLastAccess();
+ if (update) req.session.resetLastAccess();
return req.session;
};
View
@@ -8,9 +8,11 @@ var connect = require('connect')
, should = require('should')
, http = require('http');
-// store
+// constructors
-var MemoryStore = connect.session.MemoryStore;
+var MemoryStore = connect.session.MemoryStore
+ , Cookie = connect.session.Cookie
+ , Session = connect.session.Session;
// settings
@@ -625,7 +627,43 @@ module.exports = {
});
});
},
+
+ 'test Store#load(sid, fn)': function(){
+ var port = ++portno
+ , store = new MemoryStore
+ , app = connect.createServer(
+ connect.cookieParser()
+ , connect.session({ secret: 'foo', store: store })
+ , function(req, res){
+ res.end('wahoo');
+ }
+ );
+ app.listen(port, function(){
+ var options = { port: port, buffer: true };
+ http.get(options, function(res){
+ var id = decodeURIComponent(sid(res));
+ store.load(id, function(err, sess){
+ should.equal(null, err);
+ sess.should.be.an.instanceof(Session);
+ sess.cookie.should.be.an.instanceof(Cookie);
+ sess.foo = 'bar';
+ var a = sess;
+ sess.save(function(){
+ store.load(id, function(err, sess){
+ should.equal(null, err);
+ sess.should.be.an.instanceof(Session);
+ sess.cookie.should.be.an.instanceof(Cookie);
+ sess.foo.should.equal('bar');
+ a.lastAccess.should.equal(sess.lastAccess);
+ app.close();
+ });
+ });
+ });
+ });
+ });
+ },
+
'test different UA strings': function(){
++pending;

0 comments on commit 4e2feea

Please sign in to comment.