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

52
src/lib/notification.ts Normal file
View File

@@ -0,0 +1,52 @@
type Controller = ReadableStreamDefaultController;
const userClients = new Map<string, Set<Controller>>();
/**
* Thêm connection cho user
*/
export function addClient(userId: string, controller: Controller) {
if (!userClients.has(userId)) {
userClients.set(userId, new Set());
}
userClients.get(userId)!.add(controller);
}
/**
* Xoá connection khi tab đóng
*/
export function removeClient(userId: string, controller: Controller) {
const controllers = userClients.get(userId);
if (!controllers) return;
controllers.delete(controller);
// nếu user không còn tab nào mở thì xoá luôn
if (controllers.size === 0) {
userClients.delete(userId);
}
}
/**
* Gửi notification cho 1 user
*/
export function sendToUser(userId: string, data: any) {
const controllers = userClients.get(userId);
if (!controllers) return;
for (const controller of controllers) {
controller.enqueue(`data: ${JSON.stringify(data)}\n\n`);
}
}
/**
* Gửi cho tất cả user
*/
export function broadcast(data: any) {
for (const controllers of userClients.values()) {
for (const controller of controllers) {
controller.enqueue(`data: ${JSON.stringify(data)}\n\n`);
}
}
}