简体   繁体   English

我怎样才能听到会话被破坏的事件?

[英]How can I listen to session destroyed event?

I'm currently develop an application with Sails.JS. 我目前正在使用Sails.JS开发一个应用程序。

I want to count the number of online users and update it once they login/ logout or there session expire, but I don't know how to implement something like session destroyed event and can't update the number of online user whenever a session is expired without user logging out. 我想计算在线用户的数量,并在登录/退出或会话到期后更新它,但我不知道如何实现会话销毁事件之类的东西,并且无论何时会话都无法更新在线用户的数量在没有用户注销的情况下过期。

As other said above, there is no such events in the default session implementation, Sails session are close to ExpressJs Session, i recommend you to read this article about ExpressJs Sessions : 如上所述,默认会话实现中没有此类事件,Sails会话接近ExpressJs Session,我建议您阅读本文关于ExpressJs会话:

http://expressjs-book.com/forums/topic/express-js-sessions-a-detailed-tutorial/ http://expressjs-book.com/forums/topic/express-js-sessions-a-detailed-tutorial/

Then one idea in order to achieve what you want could be to use a store and query inside of it. 然后,一个想法,以实现你想要的可能是在其中使用store和查询。

Did you though about other solutions such as using socket.io (built in sails) and adding your users into a channel upon login and then simply counting user inside your channel ? 您是否考虑过其他解决方案,例如使用socket.io (内置风帆)并在登录时将用户添加到频道中,然后只是计算频道内的用户?

You can wrap the session.destroy() function like so: 您可以像这样包装session.destroy()函数:

var destroyWrapper = buildDestroyWrapper(function(req){
    //do stuff after req.destroy was called
});


function buildDestroyWrapper(afterDestroy){
    return function(req){
        req.destroy();
        afterDestroy(req);
    };
}



//later, in your controller


function controllerAction(req,res,next){
    destroyWrapper(req);
}

this method allows you to handle destruction differently, depending on what callback you pass to buildDestroyWrapper. 此方法允许您以不同方式处理销毁,具体取决于您传递给buildDestroyWrapper的回调。 For example: 例如:

var logAfterDestroy = buildDestroyWrapper(function(req){
    console.log("session destroyed");
});
var killAfterDestroy = buildDestroyWrapper(function(req){   
    process.kill();
});


function buildDestroyWrapper(afterDestroy){
    return function(req){
        req.destroy();
        afterDestroy(req);
    };
}



//later, in your controller
function logoutAction(req,res,next){
    logAfterDestroy(req);
}
function killAppAction(req,res,next){
    killAfterDestroy(req);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM