Search code examples
feathersjs

FeathersJS - Making sure only the user that registers gets "users created"


I would like to make sure that only the socket which sends a registration / "users create" message gets the according "users created" response. There is a simple example for that in the documentation looking like this:

// Publish the `created` event to admins and the user that sent it
app.service('users').publish('created', (data, context) => {
  return [
    app.channel('admins'),
    app.channel(app.channels).filter(connection =>
      connection.user._id === context.params.user._id
    )
  ];
});

However this is not working for me. If I log the context.params object, this simply looks like this when registering a new user:

{ query: {},
  route: {},
  connection: { provider: 'socketio' },
  provider: 'socketio' }

Accordingly, the appropriate connection does not get the event. Am I missing something here? Do I have to add something in the registration process for this to work? Thanks a lot!


Solution

  • The easiest solution would be to not worry about dispatching the real-time event to that user at all. If the same connection is already calling .create the result from that promise (.create(data).then(userData => {})) will be the same as the dispatched event.

    If you'd still like to have a newly created user join certain channels you can use params.connection in an after hook as shown in this issue:

    app.service('users').hooks({
      after: {
        create(context) {
          const { params: { connection }, result } = context;
    
          if(connection) {
            context.app.channel(`user/${result.id}`).join(connection);
          }
    
          return context;
        }
      }
    });