SalientBrain
SalientBrain

Reputation: 2551

Using message bus with promises and for DI/IOC

In my app I want to use "local" message bus in a particular way (extended event emitter/observer/dispatcher):

  1. In some cases I want to use it for DI/IOC. I mean that some component will be registered as a producer for some message type. For example API client can register some methods as producers: (pseudocode)
bus.producers.register("topic/entity/get", ({id}) => entityClient.get(id));

Other component will post message in the bus:

bus.post("topic/entity/get", {id: 123});

and then consume the produced result;

What are the problems with this approach? Note: consumer component will have declarative metadata config with all messages in consumes and produces.

  1. I want to use promises for consume results. It is not directly related to DI/IOC - it is about handling the "output of message handlers". So is it OK to consume bus like this:
// get first produced (normal case)
const entity = await bus.getAsyncFirst("topic/entity/get", {id: 123});
    
// collect all entities from all producers
// rare case?
    
const entities = await bus.getAsync("topic/entity/get", {id: 123}); 

?

producer implementation just need to return value for consumer.

What are potential pitfalls of this? Or it is better to use generators for collecting all produced output (instead of Promise) Shoult I post message to bus as a result (instead of just returning result). Something like

bus.producers.register("topic/entity/get", ({id}) => {
    const result = entityClient.get(id);
    bus.post("topic/entity/get/result"); // *is it better? why?*

});

I can't find examples of such using of message bus.

Upvotes: 0

Views: 35

Answers (0)

Related Questions