Added SSE function and add readAt for notification

This commit is contained in:
2026-02-21 22:34:29 +07:00
parent fa689ea4aa
commit ab745e6a2f
17 changed files with 349 additions and 43 deletions

48
src/routes/api/notify.ts Normal file
View File

@@ -0,0 +1,48 @@
import { auth } from '@/lib/auth';
import { addClient, removeClient } from '@/lib/notification';
import { createFileRoute } from '@tanstack/react-router';
import { getRequestHeaders } from '@tanstack/react-start/server';
export const Route = createFileRoute('/api/notify')({
server: {
handlers: {
GET: async ({ request }) => {
const headers = getRequestHeaders();
const session = await auth.api.getSession({ headers });
if (!session?.session.userId) {
return new Response('Unauthorized', { status: 401 });
}
const clientId = session.session.userId;
const stream = new ReadableStream({
start(controller) {
addClient(clientId, controller);
controller.enqueue(
`data: ${JSON.stringify({ type: `connected` })}\n\n`,
);
const heartbeat = setInterval(() => {
controller.enqueue(`: keepalive\n\n`);
}, 20000);
request.signal.addEventListener('abort', () => {
clearInterval(heartbeat);
removeClient(clientId, controller);
});
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
});
},
},
},
});