目前我正在尝试将一个对象与一个快速会话链接起来。
有我的代码:
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);
所以,我的问题是,我想将一个对象链接到一个会话(通常是一个 SQL 连接对象)。并在“任何地方”重新使用这个对象来执行查询等。但是当我尝试使用我的函数时,我收到以下错误消息:
“req.session.engine.connectMe 不是函数”
仅供参考,我的引擎对象和引擎工厂代码:
引擎
function engine(){
this.attributeA = "aaa";
this.attributeB = "bbb";
};
engine.prototype.connectMe = function(){
return this.attributeA + this.attributeB;
};
module.exports = engine;
引擎工厂
var engine = require('./engine');
function engineFactory() {
};
engineFactory.prototype.giveMeObject = function() {
return new engine;
};
module.exports = engineFactory;
正如我所说,目标是将 SQL 连接与用户会话链接起来。将连接提供给用户,然后,应用程序重新使用用户的连接来询问数据库(关于那个,我知道池连接模式更好,但这是这个项目的要求,原因有很多) .
但目前我不能重用对象的方法......
谢谢您的帮助。