簡體   English   中英

清除會話特定超時

[英]clear session specific timeout

我有一個快速應用程序,我在其中設置請求超時,並在滿足條件時清除另一條路由請求的超時。 問題是我不能在會話中存儲超時(這是正常的,因為它是一個函數,而不是你可以使用 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
};

然后問題是如果人們注銷或會話被破壞/刪除,我該如何清理這個文件。

我在 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

我希望這對其他人有所幫助。 我仍然不知道這是否是正確的方法,但它對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM