Files
dmail-front/src/hooks/useEmailEvents.ts
T
hamid zarghami 0778ecae76 socket and badge
2025-07-23 14:45:57 +03:30

96 lines
2.2 KiB
TypeScript

import { useEffect } from "react";
import { Socket } from "socket.io-client";
export interface EmailPayload {
messageId: number;
userId: string;
from: {
name?: string;
address: string;
};
to: Array<{
name?: string;
address: string;
}>;
subject: string;
preview?: string;
hasAttachments: boolean;
timestamp: string;
mailboxId: string;
mailboxName: string;
isRead: boolean;
isFlagged: boolean;
size: number;
}
export interface EmailStatusPayload {
messageId: number;
userId: string;
mailboxId: string;
timestamp: string;
}
export interface UnreadCountPayload {
userId: string;
totalUnread: number;
mailboxCounts: Record<string, number>;
timestamp: string;
count: number;
}
interface EmailEventHandlers {
onNewEmail?: (email: EmailPayload) => void;
onEmailRead?: (data: EmailStatusPayload) => void;
onEmailDeleted?: (data: EmailStatusPayload) => void;
onEmailSent?: (data: EmailStatusPayload) => void;
onUnreadCountUpdated?: (data: UnreadCountPayload) => void;
onMailboxUpdated?: (data: EmailStatusPayload) => void;
}
export const useEmailEvents = (
socket: Socket | null,
handlers: EmailEventHandlers
) => {
useEffect(() => {
if (!socket) return;
// Register event handlers
if (handlers.onNewEmail) {
socket.on("new_email", handlers.onNewEmail);
}
if (handlers.onEmailRead) {
socket.on("email_read", handlers.onEmailRead);
}
if (handlers.onEmailRead) {
socket.on("email_unread", handlers.onEmailRead);
}
if (handlers.onEmailDeleted) {
socket.on("email_deleted", handlers.onEmailDeleted);
}
if (handlers.onEmailSent) {
socket.on("email_sent", handlers.onEmailSent);
}
if (handlers.onUnreadCountUpdated) {
socket.on("unread_count_updated", handlers.onUnreadCountUpdated);
}
if (handlers.onMailboxUpdated) {
socket.on("mailbox_updated", handlers.onMailboxUpdated);
}
// Cleanup on unmount
return () => {
socket.off("new_email");
socket.off("email_read");
socket.off("email_deleted");
socket.off("email_sent");
socket.off("unread_count_updated");
socket.off("mailbox_updated");
};
}, [socket, handlers]);
};