mapf
mapf

Reputation: 506

Feathers - Emit Custom Event via Socket.io

I am trying to emit a custom event in a Feathers hook. I tried the following in the hook:

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

I also added the event to the service:

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

The problem is, that the event never gets emitted. With debugging I only see the following messages in the console:

debug: before app.service('groups').find()

debug: after app.service('groups').find()

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

However the event is never emitted using Socket.io. In the channels I send every event to authenticated users. I also tried changing it to everybody without success. As I run Feathers using DEBUG=* npm start I can see, that the event is never emitted. Any idea? Thanks!

Upvotes: 2

Views: 2328

Answers (1)

Daff
Daff

Reputation: 44215

This is still a little finicky at the moment. The problem is that the events array needs to be on the service when app.use is called. This can be done like this:

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

Then you can use it as documented:

groupsService.emit('list', groups)

The Feathers database services already take an events option so it would look like this:

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

Upvotes: 3

Related Questions