Home » Javascript » Layered Architecture in NodeJS

Layered Architecture in NodeJS

Posted by: admin November 1, 2017 Leave a comment

Questions:

If we’re talking about layered architecture. Should the event dispatching be inside the MessageService.create function or is it common to have it directly in the handler? The EventDispatcher is responsible for sending push notifications, emails etc. via a queue.

Some people argue that firing (domain) events should be inside your service layer. But domain events should always contain information like the authenticated user. So if I would fire events inside my MessageService, I would always need to pass the authenticated user, which I think, is a bit overkill.

The downside of this is that the handler is now coupled to HTTP, so when I want to create a batch of messages via a node script or something, the message.created will not be triggered, because it is not part of the service logic.

module.exports = async function createMessageHandler(request, reply) {
  request.log(['message', 'create']);

  const message = await MessageService.create(request.payload);

  EventDispatcher.emit('message.created', {
    message: message,
    actor: request.auth.credentials,
  });

  return reply({ data: message });
}
Answers: