1
\$\begingroup\$

So I'm using the event emitter as some sort of an event bus(If I'm allowed to call it that).

The problem I've stumbled upon is that my listeners might want different data than another listener. Since I don't want to add too much and listener specific information where things get emitted. I'm using this solution, but it feels very repetitive and not too clean.

My service function

async function updateUserStatus(userId, action) {
  const [ updatedUser ] = await User.update({ id: userId }, { status: userActions[action] });

  switch (action) {
    case actions.activate:
      UserEventEmitter.emit('user:activated', updatedUser.id);
      break;
    case actions.reject:
      UserEventEmitter.emit('user:rejected', updatedUser.id );
      break;
  }

  return updatedUser;
}

The event dispatcher/configurator

UserEventEmitter.on('user:activated', sendWelcomeMailToUser);
UserEventEmitter.on('user:activated', addActivatedComment);
UserEventEmitter.on('user:rejected', addRejectedComment);

The event listeners/handlers

async function addActivatedComment({ userId }) {
  try {
    await addComment({
      userId,
      translationKey: Enums.TIMELINE_USER_ACTIVATED
    });
  } catch (error) {
    throw new SomeGoodError(error)
  }
}

async function addRejectedComment({ userId }) {
  try {
    await addComment({
      userId,
      translationKey: Enums.TIMELINE_USER_REJECTED
    });
  } catch (error) {
    throw new SomeGoodError(error)
  }
}

function addComment({ supplierSupplierId, translationKey }) {
  return Timeline.create({
    user_id: userId,
    status: translationKey
  });
}

The addRejectedComment and addActivatedComment basically does the same thing with one different property. I don't want to send that property from the service because then my other listeners would get that property too.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.