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