我正在构建一个用户可以创建活动的应用程序,其他用户可以加入"并为事件添加评论,他们也可以打开他们之间的聊天,我有一个名为" 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.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'
});
});
该代码运行但是这向所有用户发送了一个套接字消息,我只想向事件的所有者发出警告(以及将来发送给此事件的用户)。
非常感谢你。
答案 0 :(得分:2)
watch将模型实例创建消息发送到正在观看模型的所有套接字,可以执行相同的注册而不查找通知,因为它不依赖于实例,即只调用:{{1} }
要将通知发送给单个订阅者,请使用sails.sockets
如果您想订阅,请为所有者创建一个房间:
Notification.watch(req.socket);
当你想向这个房间发布广播时:
sails.sockets.join(req.socket, owner_id);