sse => ws
This commit is contained in:
@@ -19,12 +19,12 @@ import { HomeAssistantService } from "./homeassistant/service.js";
|
||||
import { TidalClient } from "./tidal/client.js";
|
||||
import { TidalService } from "./tidal/service.js";
|
||||
import { tidalRoutes } from "./tidal/routes.js";
|
||||
import { sseRoutes } from "./sse/routes.js";
|
||||
import { sseRoutes } from "./websocket/routes.js";
|
||||
import { SseService } from "@dpu/shared";
|
||||
import { HomepageService } from "./homepage/service.js";
|
||||
import { homepageRoutes } from "./homepage/routes.js";
|
||||
import fastifySSE from "@fastify/sse";
|
||||
import fastifyCors from "@fastify/cors";
|
||||
import fastifyWebsocket from "@fastify/websocket";
|
||||
|
||||
const fastify = Fastify().withTypeProvider<ZodTypeProvider>();
|
||||
|
||||
@@ -81,7 +81,7 @@ await fastify.register(fastifyAxios, {
|
||||
},
|
||||
});
|
||||
|
||||
await fastify.register(fastifySSE);
|
||||
await fastify.register(fastifyWebsocket);
|
||||
|
||||
const haClient = new HomeAssistantClient(fastify.axios.homeassistant);
|
||||
const haService = new HomeAssistantService(haClient);
|
||||
|
||||
@@ -14,29 +14,26 @@ export async function sseRoutes(
|
||||
"/dpu/events",
|
||||
{
|
||||
schema: {
|
||||
description: "Register for SSE",
|
||||
tags: ["sse"],
|
||||
description: "Register for WebSocket events",
|
||||
tags: ["ws"],
|
||||
hide: true,
|
||||
},
|
||||
sse: true,
|
||||
websocket: true,
|
||||
},
|
||||
async (_request, reply) => {
|
||||
reply.sse.keepAlive();
|
||||
|
||||
(socket, _request) => {
|
||||
const clientId = randomUUID();
|
||||
const sendEvent = (event: SseEvent) => {
|
||||
reply.sse.send({
|
||||
event: event.type,
|
||||
data: JSON.stringify(event.data),
|
||||
});
|
||||
if (socket.readyState === socket.OPEN) {
|
||||
socket.send(JSON.stringify({ event: event.type, data: event.data }));
|
||||
}
|
||||
};
|
||||
|
||||
sseService.addClient({ id: clientId, send: sendEvent });
|
||||
|
||||
await reply.sse.send({ data: "Connected" });
|
||||
socket.send(JSON.stringify({ event: "connected", data: "Connected" }));
|
||||
logInfo(`Connection for client ${clientId} established`);
|
||||
|
||||
reply.sse.onClose(() => {
|
||||
socket.on("close", () => {
|
||||
sseService.removeClient(clientId);
|
||||
logInfo(`Connection for client ${clientId} closed`);
|
||||
});
|
||||
Reference in New Issue
Block a user