我正在使用Sails js 0.11。
按照文档here中描述的教程:
我可以创建一个pub / sub关系。但是我只想收到通知"更新"具有该字段" company = abc"的用户的事件。因此,在控制器中,我执行以下操作:
beforeCreate: function(user, next) {
//just need one sample of user from this company.
//in theory all users of this company are subscribed by same sockets
User.findOne({company:user.company}).exec(function(e,companyUser){
// Get all of the sockets that are subscribed to this user
var subscribers = User.subscribers(companyUser);
// Subscribe them all to this new user
_.each(subscribers, function(subscriber) {
User.subscribe(subscriber.id, user);
});
next();
});
这很有效。但是,如果此套接字已打开,并且创建了属于该公司的新用户,则套接字将无法接收此新用户的通知。
为了解决这个问题,我去了User模型,并添加了:
warn: `Model.subscribe()` called by a non-socket request. Only requests originating from a connected socket may be subscribed. Ignoring...
}
但是我收到了警告
$new_array = Array();
while...
我不想使用套接字创建用户。有没有解决的办法?只想让我的套接字用户保持最新状态!
由于
答案 0 :(得分:1)
实际上,将它放在afterCreate中并不会真正起作用,因为订阅者会在创建对象时收到消息,但是在创建对象之后将其放入,因此事件将不会运行。
然而,通过一个技巧,我们可以使这项工作。订阅公司而不是用户,以下是详细信息:
首先,订阅您的用户到它的公司(所有者是我的风帆应用中的公司ID):
Company.findOne({id: req.session.user.owner}).exec(function(e, company) {
Company.subscribe(req.socket, company);
});
然后,当您创建用户时,在afterCreate中,在套接字消息中查找公司ID。检索该公司的所有订户,并将其订阅到User模型的“消息”上下文。然后,在您订阅所有用户之后,通过公司模型的message()函数向他们发送“消息”类型消息。
afterCreate: function(message, next) {
Company.findOne({id: message.owner}).exec(function(e, company) {
var subscribers = Company.subscribers(company);
_.each(subscribers, function(subscriber) {
User.subscribe(subscriber, message, 'message');
});
Company.message(company, message.message);
});
next();
},
这里,消息对象是socket.io有效负载。在您将套接字客户端订阅到公司的第一部分中,您可以使用条件来指定要订阅哪个用户,甚至可以创建特定订阅者条件表,以存储所有不同的订阅通道。
希望它有所帮助。
参考文献:
http://sailsjs.org/documentation/reference/web-sockets/resourceful-pub-sub/subscribe
http://sailsjs.org/documentation/reference/web-sockets/resourceful-pub-sub/message