【发布时间】:2015-07-07 05:49:10
【问题描述】:
我正在使用 Sails js 0.11。
按照文档here 中描述的教程进行操作:
我能够创建发布/订阅关系。但是,我只想收到具有“company=abc”字段的用户的“更新”事件的通知。因此在控制器中我执行以下操作:
subscribe: function(req, res) {
User.find({company:'abc"}).exec(function(e,listOfUsers){
User.subscribe(req.socket,listOfUsers,['create','destroy']);
});
}
这行得通。但是,如果此套接字已打开,并创建了属于该公司的新用户,则套接字将不会收到此新用户的通知。
为了解决这个问题,我去了用户模型,并添加了:
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();
});
}
但是我收到警告
warn: `Model.subscribe()` called by a non-socket request. Only requests originating from a connected socket may be subscribed. Ignoring...
我不想使用套接字创建用户。有没有解决的办法?只想让我的套接字订阅者保持最新!
谢谢
【问题讨论】:
-
原来上面有两个错误。它应该是 User.subscribe(subscriber, user);,我应该在 Model.afterCreate 上调用它。但是,即使我执行 User.publishCreate({id: user.id, user:user});