feat: 整合 sse 推送

This commit is contained in:
xlsea
2024-09-02 09:34:34 +08:00
parent 6afd5cc36a
commit 89f5e8577e
15 changed files with 105 additions and 25 deletions

View File

@ -36,7 +36,7 @@ export function createServiceConfig(env: Env.ImportMeta) {
const config: App.Service.ServiceConfig = {
baseURL: httpConfig.baseURL,
ws: VITE_APP_WEBSOCKET === 'true',
ws: VITE_APP_WEBSOCKET === 'Y',
proxyPattern: VITE_APP_BASE_API,
other: otherConfig
};

45
src/utils/sse.ts Normal file
View File

@ -0,0 +1,45 @@
import { useEventSource } from '@vueuse/core';
import { watch } from 'vue';
import useNoticeStore from '@/store/modules/notice';
import { localStg } from './storage';
// 初始化
export const initSSE = (url: any) => {
if (import.meta.env.VITE_APP_SSE === 'N') {
return;
}
const token = localStg.get('token');
const sseUrl = `${url}?Authorization=Bearer ${token}&clientid=${import.meta.env.VITE_APP_CLIENT_ID}`;
const { data, error } = useEventSource(sseUrl, [], {
autoReconnect: {
retries: 10,
delay: 3000,
onFailed() {
// eslint-disable-next-line no-console
console.error('Failed to connect after 10 retries');
}
}
});
watch(error, () => {
// eslint-disable-next-line no-console
console.error('SSE connection error:', error.value);
error.value = null;
});
watch(data, () => {
if (!data.value) return;
useNoticeStore().addNotice({
message: data.value,
read: false,
time: new Date().toLocaleString()
});
window.$notification?.create({
title: '消息',
content: data.value,
type: 'success',
duration: 3000
});
data.value = null;
});
};

View File

@ -32,7 +32,7 @@ let socketError = 0; // 错误次数
// 初始化socket
export function initWebSocket(url: any) {
if (import.meta.env.VITE_APP_WEBSOCKET === 'false') {
if (import.meta.env.VITE_APP_WEBSOCKET === 'N') {
return null;
}
socketUrl = url;
@ -50,6 +50,7 @@ export function initWebSocket(url: any) {
// socket 连接成功
export function websocketonopen() {
websocket.onopen = () => {
// eslint-disable-next-line no-console
console.log('连接 websocket 成功');
resetHeart();
};
@ -58,14 +59,16 @@ export function websocketonopen() {
// socket 连接失败
export function websocketonerror() {
websocket.onerror = (e: any) => {
console.log('连接 websocket 失败', e);
// eslint-disable-next-line no-console
console.error('连接 websocket 失败', e);
};
}
// socket 断开链接
export function websocketclose() {
websocket.onclose = (e: any) => {
console.log('断开连接', e);
// eslint-disable-next-line no-console
console.warn('断开连接', e);
};
}
@ -102,9 +105,11 @@ export function reconnect() {
clearInterval(heartTime);
initWebSocket(socketUrl);
socketError += 1;
// eslint-disable-next-line no-console
console.log('socket重连', socketError);
} else {
console.log('重试次数已用完');
// eslint-disable-next-line no-console
console.warn('重试次数已用完');
clearInterval(heartTime);
}
}