1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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;
|