羽毛 - 通过Socket.io

时间:2018-06-11 16:03:02

标签: node.js socket.io feathersjs

我正在尝试在Feathers钩子中发出自定义事件。我在钩子中尝试了以下内容:

module.exports = function (options = {}) {
  return async context => {

    const { app } = context;

    const groupsService = app.service('groups');
    const groups = await groupsService.find( { query:{ members: context.result.user._id } });

    await app.emit('list', groups); // Try 1
    await groupsService.emit('list', groups); // Try 2
    await context.service.emit('list', groups); // Try3
    console.log('====================EMIT====================');

    return context;
  };
};

我还将该事件添加到服务中:

module.exports = function (app) {
  this.events = ['list']; // Try 1
  (...)
  // Get our initialized service so that we can register hooks
  const service = app.service('groups');

  service.events = ['list']; // Try 2

  service.hooks(hooks);
};

问题是,事件永远不会被发出。通过调试,我只在控制台中看到以下消息:

  

debug:在app.service('groups')之前。找到()

     

debug:在app.service('groups')之后。找到()

     

==================== EMIT ====================

但是,事件永远不会使用Socket.io发出。在频道中,我将每个事件发送给经过身份验证的用户。我也试过把它改成给大家而没有成功。当我使用DEBUG=* npm start运行Feathers时,我可以看到,事件永远不会被发出。任何的想法?谢谢!

1 个答案:

答案 0 :(得分:1)

目前这仍然有点挑剔。问题是在调用events时,app.use数组需要在服务上。这可以这样做:

module.exports = function (app) {
  (...)

  app.use('/groups', Object.assign(createService(options), {
    events: [ 'list' ]
  }));

  // Get our initialized service so that we can register hooks
  const service = app.service('groups');

  service.hooks(hooks);
};

然后你可以使用它as documented

groupsService.emit('list', groups)

Feathers数据库服务已经采用events option所以它看起来像这样:

module.exports = function (app) {
  const options = {
    (...)
    events: [ 'list' ]
  };

  app.use('/groups', createService(options));

  // Get our initialized service so that we can register hooks
  const service = app.service('groups');

  service.hooks(hooks);
};