MatthewWid / better-sse

⬆ Dead simple, dependency-less, spec-compliant server-sent events implementation for Node, written in TypeScript.
MIT License
485 stars 14 forks source link

Channel instance used in function does not get the registered session #61

Closed insivika closed 3 months ago

insivika commented 4 months ago

Hello, I have the following set up and file structure on my express project. It appears that the controller function that is accessing my channel does not have the session registered. How can I adjust the code below to be ablet to see the session and broadcast the event. Thank you

Routes

/router.js import sse from 'better-sse'; import { matchChannel } from './controllers/matches.js'; const { createSession } = sse;

router.get('/sse', async (req, res) => { const session = await createSession(req, res); matchChannel.register(session);

---- I see the Session set to 1 console.log(matchChannel); });

Match Controller

/controllers/matches.js

import sse from 'better-sse'; const { createChannel } = sse;

export const matchChannel = createChannel();

export const findAndCreateMatches = async ({ events, userId }) => { ... create matches

--- I see 0 sessions console.log('matchChannel', matchChannel); --- I dont see the matches getting broadcasted on the client matchChannel.broadcast(updatedMatches, 'matches'); })

MatthewWid commented 4 months ago

Are you able to make a minimum runnable example? I can't seem to recreate this.

If the order of events happening here is:

  1. User connects to server (GET /sse).
  2. Session is registered to matchChannel.
  3. findAndCreateMatches is called.
  4. matchChannel broadcasts.
  5. User disconnects and is deregistered at some later point after this.

Then this code should work, as it did when I ran it on my end - if not that is definitely a bug.

However, as I can't see the calling code, I assume there is something going wrong with when you are calling findAndCreateMatches. Perhaps it is getting called either before or after the session has connected or disconnected, respectively.

Try adding some debug logging to see exactly when the session is getting added and removed from the channel, and whether findAndCreateMatches is definitely being called while the session is currently connected:

matchChannel.on("session-registered", () => console.log("registered"));
matchChannel.on("session-disconnected", () => console.log("disconnected"));
matchChannel.on("session-deregistered", () => console.log("deregistered"));