pnxtech / hydra

A light-weight library for building distributed applications such as microservices
https://www.hydramicroservice.com
MIT License
645 stars 54 forks source link

sendMessage() callback functionality #203

Open aviyacohen opened 5 years ago

aviyacohen commented 5 years ago

I have 1 router service. It is listening to RESTful requests. When it gets a request it takes the post data and transfers it to another service via sendMessage(). The other process is built to take the data, process it, and return the result. The problem is that sendMessage has no callback functionality and cannot be chained with a then() to start working on the result - by either sending it to another service or routing it back to the user.

Is the only way to achieve this is by defining the process.js service as a hydra-express process with a restfulAPI? makeAPIrequest does allow for a callback function handling the response.

Another cumbersome way would be to open a different route on the router.js which will listen to the response from the service. But then how do i relay this response back to the user?

tylerhutcherson commented 3 years ago

We had the exact same use case (sorry I am late to the party here) and ended up solving it by implementing some custom code on our end. While hydra does not register a callback method out-of-the-box, it's pretty easy to construct a routing table that maps the outgoing message identifier to an anonymous callback function to handle the response.

Assuming you're sending a UMF message to some other microservice in your cluster, it's assigned a unique mid. When the downstream microservice has processed the message, it replies with an rmid that matches the mid of the initial message. When a new message arrives back to the sending service, it checks the routing table to see if there are any callbacks that need to be applied. In this case, the callback simply sends the server response object back to the HTTP client. Happy to share a small code snippet if helpful and/or if this is still an issue that you (or anyone) are facing.

tylerhutcherson commented 3 years ago

@cjus Can also likely chime in since he designed the routing table approach on our end :)