Brijesh's Git Server — server-sent-events @ 8c598439d43131b2fcf8330174264adfb6629e5a

src/index.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
import { Hono } from "hono";
import { streamSSE } from "hono/streaming";
import HtmlContent from "./html-string";

const app = new Hono();
let id = 0;

app.get("/", async (c) => {
  return c.html(HtmlContent);
});

app.get("/api/events", async (c) => {
  console.log("Client connected to SSE stream");

  return streamSSE(
    c,
    async (stream) => {
      stream.onAbort(() => {
        console.log("Client disconnected from SSE stream");
      });

      let counter = 0;

      while (true) {
        // Regular time updates
        const timeMessage = `Current time: ${new Date().toISOString()}`;
        await stream.writeSSE({
          data: timeMessage,
          event: "time-update",
          id: String(id++),
        });

        // Counter updates every 2 seconds
        if (counter % 2 === 0) {
          await stream.writeSSE({
            data: JSON.stringify({ count: counter }),
            event: "counter",
            id: String(id++),
          });
        }

        // Random data every 5 seconds
        if (counter % 5 === 0) {
          const randomValue = Math.floor(Math.random() * 100);
          await stream.writeSSE({
            data: JSON.stringify({ random: randomValue }),
            event: "random-data",
            id: String(id++),
          });
        }

        counter++;
        await stream.sleep(1000);
      }
    },
    async (err, stream) => {
      console.error("Error in SSE stream:", err);
      await stream.writeSSE({
        data: "An error occurred in the SSE stream",
        event: "error",
        id: String(id++),
      });
    },
  );
});

console.log('Hono SSE demo running at http://localhost:3000');

export default app;