sse => ws
This commit is contained in:
42
src/websocket/routes.ts
Normal file
42
src/websocket/routes.ts
Normal 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`);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user