Reputation: 705
Currently I'm trying to link an object with an express session.
There is my code :
var express = require('express');
var session = require('express-session');
// I have an object named "engine", which is a fake SQL Object connection (for example)
// this is my engineFactory (which return an engine when function "giveMeObject" is called).
var engineFactory = require('./tools/engineFactory');
var eF = new engineFactory();
// create my app
var port = 3030;
var app = express();
app.use(session({
secret: "secret"
}));
app.get('/', function(req, res) {
// Req.session.engine will contains an SQL connection
req.session.engine = eF.giveMeObject();
res.send('object gived : ' + req.session.engine); // return "object gived : [object Object]", so ok.
});
app.get('/session', function(req, res) {
// Here I verify if my engine still exists
res.send("Coming From Session: " + req.session.engine); // return "Coming From Session: [object Object]" so, ok.
});
app.get('/session-test', function(req, res) {
// Here I
res.send(Object.getOwnPropertyNames(req.session.engine)); // return ["attributeA","attributeB"], so where is my connectMe() ?
req.session.engine.connectMe(); // error : "req.session.engine.connectMe is not a function"
});
app.listen(port);
console.log('app listen to ' + port);
So, my problem is, I wanna link an object to a session (typically a SQL connection object). And re-use this object "everywhere" to execute queries, etc.
But when I try to use my function I have the following error message :
"req.session.engine.connectMe is not a function"
Just for information, my engine object, and the engine factory code :
Engine
function engine(){
this.attributeA = "aaa";
this.attributeB = "bbb";
};
engine.prototype.connectMe = function(){
return this.attributeA + this.attributeB;
};
module.exports = engine;
EngineFactory
var engine = require('./engine');
function engineFactory() {
};
engineFactory.prototype.giveMeObject = function() {
return new engine;
};
module.exports = engineFactory;
As I said, the goal is to link a SQL connection with a user session. The connection is gived to the user, then, the app re-use the user's connection to ask queries to the database (about that, I know that the pool connection pattenr is better, but this is a requirement of this project for many reasons).
But currently I can't re-use the object's method...
Thanks for the help.
Upvotes: 0
Views: 230
Reputation: 106746
Most backing session stores cannot/do not serialize complex types like functions. Many stores will simply call JSON.stringify()
on the session data and store that as-is, which will either implicitly remove functions and other complex types or it will convert them to some other type such as a plain object or a string (depending on the availability of .toJSON()
/.toString()
on the objects).
You will need to re-create the engine
instance to have access to functions and other non-serializable types.
Upvotes: 1