Files
hsl-ui/src/utils/sse.ts
T

59 lines
1.5 KiB
TypeScript
Raw Normal View History

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';
import { $t } from '@/locales';
2024-09-02 09:34:34 +08:00
import { localStg } from './storage';
/**
* 初始化 SSE
*
* @param url - SSE 地址
*/
export const initSSE = (url: string) => {
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: {
retries: 5,
delay: 5000,
2024-09-02 09:34:34 +08:00
onFailed() {
// eslint-disable-next-line no-console
console.warn('Failed to connect to SSE after 5 attempts.');
2024-09-02 09:34:34 +08:00
}
}
});
watch(error, () => {
if (!error.value || error.value?.isTrusted) {
return;
}
2024-09-02 09:34:34 +08:00
// eslint-disable-next-line no-console
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()
});
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: '消息',
content,
2024-09-02 09:34:34 +08:00
type: 'success',
duration: 3000
});
data.value = null;
});
};