43 lines
1022 B
TypeScript
Raw Normal View History

2024-07-26 16:06:17 +08:00
import { getToken } from '@/utils/auth';
import { ElNotification } from 'element-plus';
2025-03-12 12:08:23 +08:00
import { useNoticeStore } from '@/store/modules/notice';
2024-07-26 16:06:17 +08:00
// 初始化
export const initSSE = (url: any) => {
2024-10-14 20:33:16 +08:00
if (import.meta.env.VITE_APP_SSE === 'false') {
return;
}
2024-11-08 00:33:23 +08:00
url = url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID;
2024-11-26 15:29:22 +08:00
const { data, error } = useEventSource(url, [], {
2024-07-26 16:06:17 +08:00
autoReconnect: {
retries: 10,
delay: 3000,
onFailed() {
2024-10-07 10:45:25 +08:00
console.log('Failed to connect after 10 retries');
}
2024-07-26 16:06:17 +08:00
}
});
watch(error, () => {
2024-10-07 10:45:25 +08:00
console.log('SSE connection error:', error.value);
2024-07-26 16:06:17 +08:00
error.value = null;
});
watch(data, () => {
if (!data.value) return;
useNoticeStore().addNotice({
message: data.value,
read: false,
time: new Date().toLocaleString()
});
ElNotification({
title: '消息',
message: data.value,
type: 'success',
duration: 3000
});
data.value = null;
});
};