Created
August 18, 2011 22:04
-
-
Save j-mcnally/1155365 to your computer and use it in GitHub Desktop.
Express: Switch cookie sessions to a header session fore Node Apps built as APIs
This file contains hidden or 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
The two files attached are Express Middleware | |
Srvformat sets the format based on the accept header | |
to switch it to api mode. | |
ApiSession uses the req.format set by this to decide | |
which kinds of sessions to use. |
This file contains hidden or 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 apiSession(ex_session){ | |
return function apiSession(req, res, next){ | |
if (req.format != 'html') { | |
var sessionId = req.header('Sessionid'); | |
if (sessionId && sessionId != null) { | |
//try to load a sessionId | |
req.sessionStore.get(sessionId, function(err, sess){ | |
if (!err) { | |
req.sessionStore.createSession(req, sess); | |
next(); | |
} | |
else { | |
req.session.regenerate(function(err){ | |
next(); | |
}); | |
} | |
}); | |
} | |
else { | |
req.session.regenerate(function(err){ | |
next(); | |
}); | |
} | |
} | |
else { | |
next(); | |
} | |
} | |
}; |
This file contains hidden or 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 srvformat(){ | |
return function setFormat(req, res, next){ | |
var contentType = req.headers.accept; | |
if (contentType == '' || contentType == '*/*') { | |
contentType = 'html'; | |
} | |
var isBrowser = (contentType.indexOf('html') > -1); | |
req.params = req.params || {}; | |
if (isBrowser) { | |
req.params.format = req.format = 'html'; | |
} | |
else { | |
req.params.format = req.format = contentType.split('/')[1]; | |
} | |
next(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment