Files
td_official/src/utils/sse.ts

60 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-05-21 11:24:53 +08:00
import { getToken } from '@/utils/auth';
import { ElNotification } from 'element-plus';
import useNoticeStore from '@/store/modules/notice';
// 初始化
export const initSSE = (url: any) => {
if (import.meta.env.VITE_APP_SSE === 'false') {
return;
}
url = url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID;
const { data, error } = useEventSource(url, [], {
autoReconnect: {
retries: 10,
delay: 3000,
onFailed() {
console.log('Failed to connect after 10 retries');
}
}
});
watch(error, () => {
console.log('SSE connection error:', error.value);
error.value = null;
});
watch(data, () => {
2025-08-15 03:08:47 +08:00
console.log(data.value);
let label = '';
let route1 = '';
2025-08-15 10:58:12 +08:00
let detailId = '';
2025-08-15 03:08:47 +08:00
try {
if (JSON.parse(data.value)) {
const obj = JSON.parse(data.value);
route1 = obj.route;
label = obj.message;
2025-08-15 10:58:12 +08:00
detailId = obj.detailId;
2025-08-15 03:08:47 +08:00
data.value = null;
}
} catch (error) {
label = data.value;
}
2025-08-15 10:58:12 +08:00
if (!label) return;
2025-05-21 11:24:53 +08:00
useNoticeStore().addNotice({
2025-08-15 03:08:47 +08:00
message: label,
2025-05-21 11:24:53 +08:00
read: false,
2025-08-15 03:08:47 +08:00
time: new Date().toLocaleString(),
2025-08-15 10:58:12 +08:00
route: route1,
detailId: detailId
2025-05-21 11:24:53 +08:00
});
ElNotification({
title: '消息',
2025-08-15 03:08:47 +08:00
message: label,
2025-05-21 11:24:53 +08:00
type: 'success',
duration: 3000
});
data.value = null;
});
};