aboutsummaryrefslogtreecommitdiff
path: root/api/src/plugins/events.routes.ts
diff options
context:
space:
mode:
authorzwlucas <lucas.fariamo08@gmail.com>2026-07-25 21:23:29 +0000
committerzwlucas <lucas.fariamo08@gmail.com>2026-07-25 21:23:29 +0000
commitef55d9bb24430610b60c1b77821307cd72c08c55 (patch)
treee6935a810b34370b0a4c821e55f6397aac50c832 /api/src/plugins/events.routes.ts
downloadhelpdesk-ef55d9bb24430610b60c1b77821307cd72c08c55.tar.gz
helpdesk-ef55d9bb24430610b60c1b77821307cd72c08c55.zip
feat: upload of the projectHEADmaster
Signed-off-by: zwlucas <lucas.fariamo08@gmail.com>
Diffstat (limited to 'api/src/plugins/events.routes.ts')
-rw-r--r--api/src/plugins/events.routes.ts58
1 files changed, 58 insertions, 0 deletions
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<void> {
+ 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;