FoalTS / foal

Full-featured Node.js framework, with no complexity. 🚀 Simple and easy to use, TypeScript-based and well-documented.
https://foalts.org/
MIT License
1.89k stars 139 forks source link

Creating a Server-sent event #915

Closed rustyraz closed 3 years ago

rustyraz commented 3 years ago

Hi everyone. I love foalts and I am currently using it in a project. But I have feature that requires server-sent events (SSE) but I am not able to implement a response.write on the return response. But I am able to write the headers to have "'Content-Type', 'text/event-stream'"

The only challenge is creating a new res.write()

res.write(sseFormattedResponse); // express example

Thank you for your assistance in advance

woqk commented 3 years ago

@rustyraz here is my solution.

// @ts-ignore
import { Readable } from "stream";

export class XXController {
    // ....

  @Get("/listen")
  async listen(ctx: Context) {
    // @ts-ignore
    const readable = Readable.from(this.generate()) as Readable;
    const res = new HttpResponseOK(readable, { stream: true });
    res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
    res.setHeader("Cache-Control", "no-cache");
    return res;
  }

  async *generate() {
    for (let i = 0; i < 5; i++) {
      // DATA
      yield `id: ${i}\ndata: {"time": ${Date.now()}}\n\n`;
      await new Promise((r) => setTimeout(r, 2000));
    }
  }

  // ....
}
rustyraz commented 3 years ago

Thank you soooo much. This was really helpful.