MatthewWid / better-sse

⬆ Dead simple, dependency-less, spec-compliant server-sent events implementation for Node, written in TypeScript.
https://matthewwid.github.io/better-sse/
MIT License
559 stars 14 forks source link

Allow passing initial session and channel state in constructor #68

Closed MatthewWid closed 3 months ago

MatthewWid commented 3 months ago

This PR adds the ability to initialize the value of the state property in the Session and Channel constructor options objects.

While enabling the user to construct and set the session/channel state in a single statement, this also allows the TypeScript compiler to automatically infer the state type from the given state value, rather than it having to explicitly defined by passing a type/interface to the State generic.


Before:

interface SessionState {
  id: string;
}

const session = await createSession<SessionState>(req, res);

session.state.id = "123";

session.state.id = 456; // Error!

After:

const session = await createSession(req, res, {
  state: {
    id: "123"
  }
});

session.state.id = 456; // Error!