我正在构建一个应用程序,用户可以在其中创建事件,其他用户可以“加入”并向事件添加评论,还可以在它们之间打开聊天。我有一个名为“ Notification”的模型,我要将所有通知存储在系统,并且当用户对事件进行评论,向他发送新消息等时,我想警告事件的所有者。
这是我编写的注释代码的一部分:
通知模型:
/* Notification.js */
module.exports = {
attributes: {
title: {
type: 'string',
required: true
},
text: {
type: 'string'
},
type:{
type: 'string',
enum: ['new_assistant', 'cancel_assistant', 'new_message', 'new_comment'],
required: 'true'
},
read: {
type: 'boolean',
defaultsTo: false
},
user: {
model: 'user'
}
}
};
这是我向套接字订阅他的通知模型的地方:
Notification.find({
user: owner_id
}).then(function(notifications) {
return Notification.watch(req.socket);
});
每当用户在事件中发表评论时,我都会创建一个新的Notification记录:
Notification.create({
title: 'A new user has comment',
text: "Hola",
type: 'new_comment',
read: false,
user: event.owner
}).then(function(comment) {
return Notification.publishCreate({
id: notification.id,
title: 'A new user has comment'
});
});
该代码运行了,但是这向所有用户发送了一条套接字消息,我只想警告该事件的所有者(将来还会警告该事件的用户)。
非常感谢。
最佳答案
watch将模型实例创建消息发送到正在监视模型的所有套接字,由于未依赖于实例的通知,因此可能执行了相同的注册而未找到通知,即仅调用:Notification.watch(req.socket);
要将通知发送给单个订阅者,请使用sails.sockets
要订阅时为所有者创建一个房间:
sails.sockets.join(req.socket, owner_id);
而当您要将广播发布到此会议室时:
Notification.create({
title: 'A new user has comment',
text: "Hola",
type: 'new_comment',
read: false,
user: event.owner
}).then(function(comment) {
sails.sockets.broadcast(event.owner, {
id: notification.id,
title: 'A new user has comment'
});
});