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

event not emitted #48

Closed aanishacharyaa closed 1 year ago

aanishacharyaa commented 1 year ago

Session

Extends from EventEmitter.

A Session represents an open connection between the server and the client.

It emits the connected event after it has connected and flushed all headers to the client, and the disconnected event after client connection has been closed.

=> It emits disconnected event but connected event is not being emitted

const session = await createSession(req, res)

session.on("connected",() => { console.log("user "+req.user+" connected") })

session.on("disconnected",()=> { console.log("user "+req.user+" disconnected") })

})

MatthewWid commented 1 year ago

createSession waits for the session to connect before its promise is resolved, so once you go past that line it's already connected and the event has already been fired on the returned session object.

If you want to run some code that touches the session before it has connected you can construct the underlying Session class directly and then wait for the event manually:

import { Session } from "better-sse";

const session = new Session(req, res);

// Do something...

session.on("connected",() => {
  console.log("user "+req.user+" connected")
})

session.on("disconnected",()=> {
  console.log("user "+req.user+" disconnected")
})

Though I wouldn't recommend doing this unless you absolutely need to.