dan-cooke / remix-sse

Server Sent Events (SSE) for the remix framework
Apache License 2.0
78 stars 3 forks source link

How to trigger a send from outside the EventStream? #7

Closed vcheeze closed 1 year ago

vcheeze commented 1 year ago

Hi @dan-cooke, thanks for the handy library. This is really more a question than an issue:

I have a use case where I need to trigger sending data to the stream originating from another source that will call an API I expose. I've tried using a Node.js EventEmitter to no avail. It seems like attaching an EventEmitter.on handler in Remix's loader function does not work - I've tried attaching it outside, right after the EventEmitter is instantiated, and that works. Do you have any idea how I might be able to achieve this using your library?

DanFVR commented 1 year ago

@vcheeze hey! Thank you!

So if I understand your use case - you want to trigger a send from within the EventStream but based on some external API retrieving data?

This is actually why i built this library in the first place, I use Polygons Stock market websocket data alongside this library to stream live stock market data to my remix apps.

i can get you an example later, but have you had a look at the example directory?

You would just connect to your external source from within the EventStream and trigger the send function whenever you receive data

vcheeze commented 1 year ago

Thanks @DanFVR! What a quick response. Actually, my connection to the external source is not through a socket, but rather any time the external source is sending new data, it calls an API endpoint in my app, say /api/newData. My question is then, how do I trigger a send in my SSE resource route, i.e. /sse/data, from within the /api/newData handler?

I've seen examples (this is how I found your library, actually) using EventEmitter from node:events, but somehow attaching the event listener (emitter.on) in Remix's loader function doesn't seem to work. I was trying to see if I can emit an event from my /api/newData route and handle it in my SSE resource route.

vcheeze commented 1 year ago

Hey @DanFVR, just want to let you know I figured out what the issue was. For the dev environment, I had to set the emitter to a global variable like:

if (process.env.NODE_ENV === "production") {
  emitter = new EventEmitter();
} else {
  if (!global.__emitter) {
    global.__emitter = new EventEmitter();
  }
  emitter = global.__emitter;
}

This did the trick for me. Again, thanks for your help!

dan-cooke commented 1 year ago

Awesome, little bit of rubber ducking there 🦆 - but glad you solved it