From ef55d9bb24430610b60c1b77821307cd72c08c55 Mon Sep 17 00:00:00 2001 From: zwlucas Date: Sat, 25 Jul 2026 18:23:29 -0300 Subject: feat: upload of the project Signed-off-by: zwlucas --- api/src/plugins/events.routes.ts | 58 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 api/src/plugins/events.routes.ts (limited to 'api/src/plugins/events.routes.ts') diff --git a/api/src/plugins/events.routes.ts b/api/src/plugins/events.routes.ts new file mode 100644 index 0000000..fd14732 --- /dev/null +++ b/api/src/plugins/events.routes.ts @@ -0,0 +1,58 @@ +/** + * events.routes.ts + * + * Endpoint SSE (Server-Sent Events). + * Mantém a conexão aberta e repassa eventos do `fastify.events` para o cliente. + */ + +import fp from 'fastify-plugin'; +import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'; + +async function eventsRoutes(fastify: FastifyInstance): Promise { + fastify.get('/', { + schema: { + tags: ['Dashboard'], + summary: 'Stream de eventos em tempo real (SSE)', + }, + preHandler: [fastify.authenticate], + handler: (request: FastifyRequest, reply: FastifyReply) => { + // 1. Configura os headers para SSE + reply.raw.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + 'Connection': 'keep-alive', + }); + reply.raw.write('\n'); // Garante envio do header imediato + + // Helper para formatar pacote SSE + const sendEvent = (event: string, data: any) => { + reply.raw.write(`event: ${event}\n`); + reply.raw.write(`data: ${JSON.stringify(data)}\n\n`); + }; + + // 2. Registra os listeners + const onTicketCreated = (data: any) => sendEvent('ticket.created', data); + const onTicketUpdated = (data: any) => sendEvent('ticket.updated', data); + const onCommentAdded = (data: any) => sendEvent('comment.added', data); + + fastify.events.on('ticket.created', onTicketCreated); + fastify.events.on('ticket.updated', onTicketUpdated); + fastify.events.on('comment.added', onCommentAdded); + + // Ping a cada 30s para manter a conexão ativa (evitar timeout do LB/Nginx) + const pingInterval = setInterval(() => { + reply.raw.write(':\n\n'); // SSE comment block serve como heartbeat + }, 30000); + + // 3. Limpeza quando o cliente desconecta + request.raw.on('close', () => { + clearInterval(pingInterval); + fastify.events.off('ticket.created', onTicketCreated); + fastify.events.off('ticket.updated', onTicketUpdated); + fastify.events.off('comment.added', onCommentAdded); + }); + }, + }); +} + +export default eventsRoutes; -- cgit v1.2.3