清除特定于会话的超时



我有一个快速应用程序,我可以在其中设置请求超时,并在满足条件时清除另一个路由的请求超时。问题是我无法在会话中存储超时(这是正常的,因为它是一个函数,而不是您可以 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作为键,但我不确定这是否必要和/或做这样的事情的正确方法。

这就是我实现这一点的方式:

我创建一个带有空对象的新 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
};

然后问题是,如果人们注销或会话被销毁/删除,我该如何清理此文件。

我在应用程序.js文件中导出了我的商店:

exports.app = app;
exports.store = store;

这就是我清理服务器.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

我希望这对其他人有所帮助。我仍然不知道这是否是正确的方法,但它对我有用。

最新更新