From 5d2d9a6f61b74e694fd953c3180058212cd2309e Mon Sep 17 00:00:00 2001 From: i548450 Date: Tue, 9 Jun 2026 13:04:08 +0800 Subject: [PATCH] =?UTF-8?q?refactor(sse):=20wire=20=E5=BD=A2=E6=80=81?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=20SseEnvelope{msgType,=20data}?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 'notice' event handler 解析 envelope,从 data 取 title/message - 抽 parseEnvelope 通用函数,校验 msgType 必填 --- src/utils/sse.ts | 50 ++++++++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/src/utils/sse.ts b/src/utils/sse.ts index d1463cc2..dbd3b500 100644 --- a/src/utils/sse.ts +++ b/src/utils/sse.ts @@ -4,12 +4,17 @@ import { useNoticeStore } from '@/store/modules/notice'; import { getSseEventBus } from '@/utils/sseEventBus'; /** - * Strongly-typed payload of the unified "notice" SSE event. - * Backend sends one of: LOGIN_WELCOME, WORKFLOW_TASK, SYSTEM_NOTICE - * (all share the same shape — type field for dispatching, title + message for display). + * Strongly-typed SSE envelope shared by every event: + * { msgType: "...", data: { ...business fields... } } + * Frontend dispatches by msgType, then casts data to the corresponding shape. */ -interface NoticePayload { - type: string; +interface SseEnvelope { + msgType: string; + data: T; +} + +/** data shape under msgType in {LOGIN_WELCOME, WORKFLOW_TASK, SYSTEM_NOTICE} */ +interface NoticeData { title: string; message: string; } @@ -31,29 +36,40 @@ export const initSSE = (url: any) => { connect(url); }; +function parseEnvelope(raw: string): SseEnvelope | null { + try { + const env = JSON.parse(raw); + if (env && typeof env === 'object' && typeof env.msgType === 'string') { + return env as SseEnvelope; + } + console.warn('SSE: payload missing msgType', raw); + return null; + } catch (err) { + console.warn('SSE: invalid JSON envelope', raw, err); + return null; + } +} + function connect(url: string) { const fullUrl = url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID; eventSource = new EventSource(fullUrl); - // "notice" event: login welcome / workflow / system announcement — strongly-typed JSON payload + // "notice" event: login welcome / workflow task / system announcement. + // All three share NoticeData shape; msgType differentiates the source. eventSource.addEventListener('notice', (e: MessageEvent) => { if (!e.data) return; - let payload: NoticePayload; - try { - payload = JSON.parse(e.data); - } catch (err) { - console.warn('SSE notice: invalid JSON payload', e.data, err); - return; - } + const env = parseEnvelope(e.data); + if (!env) return; + const { title, message } = env.data; useNoticeStore().addNotice({ - title: payload.title, - message: payload.message, + title, + message, read: false, time: new Date().toLocaleString() }); ElNotification({ - title: payload.title, - message: payload.message, + title, + message, type: 'success', duration: 3000 });