From 19513dac52a4b29c807790a97ea6eac97912570b Mon Sep 17 00:00:00 2001 From: ah-max150 Date: Sat, 15 Aug 2026 11:40:36 +0800 Subject: [PATCH] feat: sse --- .../apps/web-antd/src/api/notify/sse.ts | 28 ++++++------------- 1 file changed, 8 insertions(+), 20 deletions(-) diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/notify/sse.ts b/ecom-dmb-frontend/apps/web-antd/src/api/notify/sse.ts index 28cd25c2..7a1eb792 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/notify/sse.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/notify/sse.ts @@ -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) {