2024-09-02 09:34:34 +08:00
|
|
|
import { watch } from 'vue';
|
2025-04-23 16:02:41 +08:00
|
|
|
import { useEventSource } from '@vueuse/core';
|
2026-03-10 16:25:43 +08:00
|
|
|
import { useNoticeStore } from '@/store/modules/notice';
|
2025-09-12 10:04:36 +08:00
|
|
|
import { $t } from '@/locales';
|
2024-09-02 09:34:34 +08:00
|
|
|
import { localStg } from './storage';
|
|
|
|
|
|
2025-11-19 18:10:11 +08:00
|
|
|
/**
|
|
|
|
|
* 初始化 SSE
|
|
|
|
|
*
|
|
|
|
|
* @param url - SSE 地址
|
|
|
|
|
*/
|
|
|
|
|
export const initSSE = (url: string) => {
|
2024-09-11 14:36:46 +08:00
|
|
|
const token = localStg.get('token');
|
|
|
|
|
if (import.meta.env.VITE_APP_SSE === 'N' || !token) {
|
2024-09-02 09:34:34 +08:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
const sseUrl = `${url}?Authorization=Bearer ${token}&clientid=${import.meta.env.VITE_APP_CLIENT_ID}`;
|
|
|
|
|
const { data, error } = useEventSource(sseUrl, [], {
|
|
|
|
|
autoReconnect: {
|
2025-12-06 16:37:25 +08:00
|
|
|
retries: 5,
|
|
|
|
|
delay: 5000,
|
2024-09-02 09:34:34 +08:00
|
|
|
onFailed() {
|
|
|
|
|
// eslint-disable-next-line no-console
|
2025-12-06 16:37:25 +08:00
|
|
|
console.warn('Failed to connect to SSE after 5 attempts.');
|
2024-09-02 09:34:34 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
watch(error, () => {
|
2025-12-06 16:37:25 +08:00
|
|
|
if (!error.value || error.value?.isTrusted) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2024-09-02 09:34:34 +08:00
|
|
|
// eslint-disable-next-line no-console
|
2025-12-06 16:37:25 +08:00
|
|
|
console.error('SSE connection error:\n', error.value);
|
2024-09-02 09:34:34 +08:00
|
|
|
error.value = null;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
watch(data, () => {
|
|
|
|
|
if (!data.value) return;
|
|
|
|
|
useNoticeStore().addNotice({
|
|
|
|
|
message: data.value,
|
|
|
|
|
read: false,
|
|
|
|
|
time: new Date().toLocaleString()
|
|
|
|
|
});
|
2025-09-12 10:04:36 +08:00
|
|
|
let content = data.value;
|
|
|
|
|
const noticeType = content.match(/\[dict\.(.*?)\]/)?.[1];
|
|
|
|
|
if (noticeType) {
|
|
|
|
|
content = content.replace(`dict.${noticeType}`, $t(`dict.${noticeType}` as App.I18n.I18nKey));
|
|
|
|
|
}
|
2024-09-02 09:34:34 +08:00
|
|
|
window.$notification?.create({
|
|
|
|
|
title: '消息',
|
2025-09-12 10:04:36 +08:00
|
|
|
content,
|
2024-09-02 09:34:34 +08:00
|
|
|
type: 'success',
|
|
|
|
|
duration: 3000
|
|
|
|
|
});
|
|
|
|
|
data.value = null;
|
|
|
|
|
});
|
|
|
|
|
};
|