我有一个Express应用程序,其中我对请求设置了超时,并在满足条件时根据另一条路线的请求清除了超时。问题是我无法在会话中存储超时(这是正常现象,因为它是一个函数,而不是可以使用JSON.stringify()的东西)。
我尝试制作一个全局变量:让超时并为该变量分配超时,但这不能正常进行,因为我有多个用户。因此,每次其他用户发送请求时,都会重新分配超时变量。
我想做什么的一个小例子:
const route1 = (req, res) => {
const timeout = setTimeout(() => {
// do something
}, 1000);
req.session.timeout = timeout; // I know this does not work, but it is an example of what I would like to do
};
const route2 = (req, res) => {
// if condition is met clear the above timeout for this user/session
clearTimeout(req.session.timeout); // I know this does not work, but it is an example of what I would like to do
};
我可以使用sessionId作为关键字将每个超时存储在一个对象中,但是我不确定这是必需的和/或执行类似操作的正确方法。
答案 0 :(得分:0)
这就是我实现这一目标的方式:
我创建了一个带有空对象的新JS文件:
let mapper = {
};
module.exports = mapper;
这是我的用法:
const route1 = (req, res) => {
const {id: sessionId} = req.session;
const timeout = setTimeout(() => {
// do something
}, 1000);
mapper[sessionId] = timeout; // I put the timeout instance in the object with as key the sessionId
};
const route2 = (req, res) => {
const {id: sessionId} = req.session;
// if condition is met clear the above timeout for this user/session
clearTimeout(mapper[sessionId]); // I get the Timeout instance from the object
};
然后的问题是,如果人们注销或会话被破坏/删除,我该如何清理此文件。
我将商店导出到我的app.js文件中
exports.app = app;
exports.store = store;
这是我清理server.js文件中的映射器对象的方式:
const mapper = require('./mapperFile');
const store = require('./app').store;
setInterval(() => {
const ids = Object.keys(mapper);
for (let i = 0; i< ids.length; i++) { // I loop through all the sessionIds (the keys of the Object)
store.get(ids[i], (err, store) => { // I get the store for this key
if (err) {
// console.log(err);
}
else {
if (!store) {
delete mapper[ids[i]]; // If the session is removed I delete this from the object
}
}
});
}
}, 2000); // I don't know if 2 seconds is a good time but you get the idea
我希望这可以帮助其他人。我仍然不知道这是否是正确的方法,但这对我有用。