sse => ws

This commit is contained in:
Darius
2026-02-06 10:08:36 +01:00
parent 18708add17
commit 5866216e36
4 changed files with 189 additions and 46 deletions

42
src/websocket/routes.ts Normal file
View File

@@ -0,0 +1,42 @@
import type { FastifyInstance } from "fastify";
import { logInfo, type SseEvent, type SseService } from "@dpu/shared";
import { randomUUID } from "node:crypto";
export async function sseRoutes(
fastify: FastifyInstance,
{
sseService,
}: {
sseService: SseService;
},
) {
fastify.get(
"/dpu/events",
{
schema: {
description: "Register for WebSocket events",
tags: ["ws"],
hide: true,
},
websocket: true,
},
(socket, _request) => {
const clientId = randomUUID();
const sendEvent = (event: SseEvent) => {
if (socket.readyState === socket.OPEN) {
socket.send(JSON.stringify({ event: event.type, data: event.data }));
}
};
sseService.addClient({ id: clientId, send: sendEvent });
socket.send(JSON.stringify({ event: "connected", data: "Connected" }));
logInfo(`Connection for client ${clientId} established`);
socket.on("close", () => {
sseService.removeClient(clientId);
logInfo(`Connection for client ${clientId} closed`);
});
},
);
}