feat: sse

This commit is contained in:
2026-08-15 11:40:36 +08:00
parent 949c5dcf0c
commit 19513dac52
@@ -3,8 +3,6 @@ import { useAccessStore } from '@vben/stores';
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
const DEVICE_ID_KEY = 'ecom-dmb:realtime-sse-device-id';
/** SSE 事件名(与后端 RealtimeSseEvents 对齐) */
export const RealtimeSseEvent = {
CONNECTED: 'message',
@@ -17,26 +15,16 @@ export const RealtimeSseEvent = {
export type RealtimeSseEventName =
(typeof RealtimeSseEvent)[keyof typeof RealtimeSseEvent];
function resolveDeviceId(): string {
try {
const existing = sessionStorage.getItem(DEVICE_ID_KEY);
if (existing) {
return existing;
}
const id = crypto.randomUUID
? crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
sessionStorage.setItem(DEVICE_ID_KEY, id);
return id;
} catch {
return crypto.randomUUID
? crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
}
function createDeviceId(): string {
return crypto.randomUUID
? crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
}
/**
* 用户级 SSE 连接(同标签页复用 deviceId;多标签页各自独立)
* 用户级 SSE 连接。
* deviceId 仅存本页内存:避免 Chrome「复制标签」复制 sessionStorage 导致同 id 互踢。
* 同标签重连会换新 id;旧连接已 disconnect,服务端靠回调清理即可。
*/
export class RealtimeSseConnection {
private eventSource: EventSource | null = null;
@@ -48,7 +36,7 @@ export class RealtimeSseConnection {
private intentionalClose = false;
constructor() {
this.deviceId = resolveDeviceId();
this.deviceId = createDeviceId();
}
addEventListener(eventType: string, handler: (event: MessageEvent) => void) {