Last active
August 29, 2015 14:03
-
-
Save hoshi-takanori/4c737679590e15511a23 to your computer and use it in GitHub Desktop.
Create my own session store for Express 4.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var cookieParser = require('cookie-parser'); | |
var session = require('express-session'); | |
var MyMemoryStore = require('./MyMemoryStore')(session); | |
var app = express(); | |
... | |
app.use(cookieParser()); | |
app.use(session({ | |
store: new MyMemoryStore({ debug: true }), | |
secret: process.env.SESSION_SECRET || 'session secret' | |
})); | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function (session) { | |
var Store = session.Store; | |
function MyMemoryStore(options) { | |
Store.call(this, options || {}); | |
this.debug = options && options.debug; | |
this.sessions = {}; | |
} | |
MyMemoryStore.prototype.__proto__ = Store.prototype; | |
MyMemoryStore.prototype.get = function (sid, fn) { | |
var sess = this.sessions[sid]; | |
if (this.debug) console.log('MyMemoryStore.get: sid = ' + sid + ', sess = ' + sess); | |
if (sess) { | |
sess = JSON.parse(sess); | |
setImmediate(fn, null, sess); | |
} else { | |
setImmediate(fn); | |
} | |
} | |
MyMemoryStore.prototype.set = function (sid, sess, fn) { | |
sess = JSON.stringify(sess); | |
if (this.debug) console.log('MyMemoryStore.set: sid = ' + sid + ', sess = ' + sess); | |
this.sessions[sid] = sess; | |
fn && setImmediate(fn); | |
} | |
MyMemoryStore.prototype.destroy = function (sid, fn) { | |
if (this.debug) console.log('MyMemoryStore.destroy: sid = ' + sid); | |
delete this.sessions[sid]; | |
fn && setImmediate(fn); | |
} | |
return MyMemoryStore; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment