add better sse handling

This commit is contained in:
Darius
2026-02-05 04:34:14 +01:00
parent 4db61998bd
commit 0043b75c95
4 changed files with 37 additions and 14 deletions

View File

@@ -23,6 +23,7 @@ import { sseRoutes } from "./sse/routes.js";
import { SseService } from "@dpu/shared";
import { HomepageService } from "./homepage/service.js";
import { homepageRoutes } from "./homepage/routes.js";
import fastifySSE from "@fastify/sse";
const fastify = Fastify().withTypeProvider<ZodTypeProvider>();
@@ -73,6 +74,8 @@ await fastify.register(fastifyAxios, {
},
});
await fastify.register(fastifySSE);
const haClient = new HomeAssistantClient(fastify.axios.homeassistant);
const haService = new HomeAssistantService(haClient);

View File

@@ -1,5 +1,6 @@
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { SseService } from "@dpu/shared";
import { logInfo, SseEvent, SseService } from "@dpu/shared";
import { randomUUID } from "crypto";
export async function sseRoutes(
fastify: FastifyInstance,
@@ -22,25 +23,27 @@ export async function sseRoutes(
tags: ["sse"],
hide: true
},
sse: true
},
async (request, reply) => {
reply.raw.setHeader("Content-Type", "text/event-stream");
reply.raw.setHeader("Cache-Control", "no-cache");
reply.raw.setHeader("Connection", "keep-alive");
reply.sse.keepAlive()
const clientId = Date.now();
const sendEvent = (data: unknown) => {
reply.raw.write(`data: ${JSON.stringify(data)}\n\n`);
const clientId = randomUUID();
const sendEvent = (data: SseEvent) => {
reply.sse.send({
data: JSON.stringify(data)
});
};
sseService.addClient({ id: clientId, send: sendEvent });
sendEvent({ type: "connected", message: "SSE connected" });
await reply.sse.send({ data: 'Connected' });
logInfo(`Connection for client ${clientId} established`);
request.raw.on("close", () => {
sseService.removeClient(clientId);
});
reply.sse.onClose(() => {
sseService.removeClient(clientId);
logInfo(`Connection for client ${clientId} closed`);
})
},
);
}