javascript - 仅向模型所有者广播消息

标签 javascript node.js sockets socket.io sails.js

我正在构建一个应用程序,用户可以在其中创建事件,其他用户可以“加入”并向事件添加评论,他们也可以在他们之间打开聊天,我有一个名为“通知”的模型,我想在其中存储所有系统中的通知,每当用户评论他的事件、给他写新消息等时,我想向事件的所有者发出警告。

这是我编写的注释代码部分:

通知模型:

/* 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'
  });
});

该代码运行,但这向所有用户发送了一条套接字消息,我只想警告该事件的所有者(以及将来参加该事件的用户)。

非常感谢。

最佳答案

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'
  });
});

关于javascript - 仅向模型所有者广播消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31154144/

相关文章:

c++ - Node :How to call c++ DLL function through nodejs?

Java Socket 编写器

sockets - 使用 SIOCGIFINDEX 获取接口(interface)索引时出错

c++ - 从多个线程在同一个套接字上发布许多 wsasend

javascript - 我的应用无法多次向 Firebase 发送相同的数据结构

javascript - onValueChange 不适用于现有组件

javascript - 为没有 API 的网站创建 YQL

javascript - 如何在 NodeJs 中将 Redis 值检索到数组中

dom - 使用 node.js 解析 html 页面的首选 DOM 库?

node.js - 在 Express REST API 中使用 OOP 的最佳方式?