diff --git a/README.md b/README.md index 35d37a1..5212e24 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,12 @@ You can see your session id (sid) into the response header: See full documentation into _doc_ folder. +## Modifying session data +Whenever modified the req.session data, remember execute `req.saveSession()` immediately, otherwise the newly modified data will be lost at the next time when new request comes in + +## Destroy session +Execute `req.destroySession()` to clear the session data in the Redis + ## Run Tests All tests are written in mocha and designed to be run with npm: @@ -69,4 +75,4 @@ All tests are written in mocha and designed to be run with npm: [1]: https://www.npmjs.org/package/restify [2]: http://redis.io -[3]: https://www.npmjs.org/package/phonegap \ No newline at end of file +[3]: https://www.npmjs.org/package/phonegap diff --git a/lib/restify-session.js b/lib/restify-session.js index 0c6ce31..d69a289 100644 --- a/lib/restify-session.js +++ b/lib/restify-session.js @@ -494,7 +494,7 @@ module.exports = function(config) { if (!loadErr) { session.setSessionData(reqSid, data, req, res, next); } else { - next(); + nextFlow(); } }); } else { @@ -502,11 +502,37 @@ module.exports = function(config) { if (!createErr) { session.setSessionData(sid, {}, req, res, next); } else { - next(); + nextFlow(); } }); } }); + + // For the saveSession feature + var fakeRes = {setHeader: function(sidHeader, sid){return;}} + var nextFlow = function(){ + // Define the saveSession function for every req instance + if(!req.saveSession || typeof req.saveSession !== 'function'){ + req.saveSession = function(cb){ + if(this.session && this.session.sid) + sessionManager.setSessionData(this.session.sid, this.session, this, fakeRes, function(){ + if(cb && typeof cb === 'function') cb(); + }); + else if(cb && typeof cb === 'function') cb(); + } + } + + // Define the destroySession function for every req instance + if(!req.destroySession || typeof req.destroySession !== 'function'){ + req.destroySession = function(cb){ + if(this.session && this.session.sid) + sessionManager.destroy(this.session.sid, cb); + else if(cb && typeof cb === 'function') cb(); + } + } + next(); + } + }; return session;