在策略中过滤通知

无论何时创build模型(或删除/修改),每个连接的套接字都会通过Sails autowatch设置进行通知。 这在一定程度上是好的,但我想在某个时候过滤这些通知。

我的应用程序有自己的“通知”,应该发送到各自的接收器。 所以他们的解剖有点像: id, message, receiver, sender

身份validation是本地护照实施。

监听notification事件会导致在每次创build通知时收到通知。

 // client: app.js io.socket.on('notification', function(evt) { console.log(evt); }); 

我现在试图实现的是过滤这些通知以匹配用户ID。 我写了一个适用于/notification事件的策略。

 // Policy: forUser module.exports = function(req, res, next) { // ... whatever ... // return next(); } 

在政策内

  'notification': { 'create': ['passport', 'forUser'] } 

我现在的问题是:如何实施这个政策? 我想只是检查notification.receiver == req.user.id ,但如何获得政策内的通知模型(如果这是正确的方式)呢?

谢谢。

编辑 :尝试实施房间的解决scheme,但我没有得到任何通知在客户端上。

我在我的NotificationController中更改了我的订阅function:

 subscribe: function(req, res) { sails.log.info('Your user id: ' + req.user.id); sails.sockets.join(req.socket, 'user_notifications_' + req.user.id); res.json({ room: 'user_notifications_' + req.user.id }); }, 

并在我的模型中添加了一个afterCreate方法:

 afterCreate: function(model, next) { sails.sockets.broadcast('user_notifications_' + model.receiver, { test: 'hello' }); next(); } 

现在的客户端代码是:

  io.socket.get("/notification/subscribe", function(data, jwr) { io.socket.on(data.room, function(obj) { console.log(obj); }); }); 

订阅方法被调用并返回正确的房间名称。 但是在调用/notification/create?message=test&receiver=1时,我没有收到任何消息。 afterCreate方法被调用,所有的用户ID都是正确的(因为只有一个用户),但没有任何反应。

编辑2:好像join房间失败。

 sails.sockets.join(req.socket, 'testroom'); // For testing sails.log.debug(sails.sockets.socketRooms(req.socket)); 

房间被创build,但套接字没有订阅它。

编辑3: find解决scheme。 接口完成后,我会立即发布GitHub链接。

你使用sails.sockets.blast()发送你的通知?

要发送自定义事件,可以使用sails.sockets.emit()

 // Controller action actionSendingNotification: function(req, res) { // Retrieve the user socket ID and the data to send // ... sails.sockets.emit(userSocketId, 'notification', data); } 

您必须能够知道用户是否有活动的WebSocket连接并检索其套接字ID。 他可以在浏览器中打开几个选项卡,并可以连接几个websocket …

可能更好的解决scheme是使用sails.sockets.join()和sails.sockets.broadcast() 。 然后,您将在连接的用户socket.io 观察到的事件之间创build关联。

 // When the user creates a websocket connection, subscribe him to the model room // This action MUST be called by a websocket request // Here I assume your event is related to a model subscribeToModelRoom: function(req, res) { var roomName = 'myModelRoom' + req.param('model_id'); sails.sockets.join(req.socket, roomName); res.json({ message: 'Subscribed to a room called '+roomName+'!' }); } 

然后,每当您向该房间发送消息时,订阅的用户都会收到该消息。

 // When the model has to send a notification, use broadcast() to send it to the room associated to the model. sails.sockets.broadcast('myModelRoom' + modelInstance.id, 'notification', data); 

编辑再次读你的问题,我会添加一些解释。

看来你试图发送你的通知给用户,基于他的user.id 当你发送这个通知时,你不能假设这个用户将通过websocket连接。 您不会将事件发送给用户,而是发送到打开的websocket连接 (可能会被authentication)。

如果用户不能错过通知,则必须将其存储在数据库中。 当他将被连接时,您将显示给用户。

如果您希望在连接时实时通知用户,则可以在初始化其身份validation的WebSocket连接时将其订阅到"user_notifications_" + user.id房间。 然后在创build新通知时向这个房间发送一个事件。

您可以添加逻辑来pipe理看到/未看到的通知,并删除过时的logging。

这样,您可以实时向用户发送信息,如果没有人接收信息,则不会丢失信息。