mailbox/backend/services/sseService.js

49 lines
1 KiB
JavaScript
Raw Permalink Normal View History

2025-12-16 08:18:15 +09:00
/**
* Server-Sent Events (SSE) 서비스
* 실시간 메일 수신 알림
*/
const clients = new Set();
/**
* 클라이언트 연결 추가
*/
exports.addClient = (res) => {
clients.add(res);
console.log(`[SSE] 클라이언트 연결: 총 ${clients.size}`);
};
/**
* 클라이언트 연결 제거
*/
exports.removeClient = (res) => {
clients.delete(res);
console.log(`[SSE] 클라이언트 연결 해제: 총 ${clients.size}`);
};
/**
* 모든 클라이언트에게 메일 알림 전송
*/
exports.notifyNewMail = (mailData) => {
const message = JSON.stringify({
type: "new-mail",
data: {
from: mailData.from,
to: mailData.to,
subject: mailData.subject,
date: mailData.date,
},
});
console.log(`[SSE] 새 메일 알림 전송: ${clients.size}명에게`);
clients.forEach((client) => {
try {
client.write(`data: ${message}\n\n`);
} catch (error) {
console.error("[SSE] 메시지 전송 실패:", error);
clients.delete(client);
}
});
};