sse.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { getToken } from '@/utils/auth';
  2. import { ElNotification } from 'element-plus';
  3. import useNoticeStore from '@/store/modules/notice';
  4. // 初始化
  5. export const initSSE = (url: any) => {
  6. if (import.meta.env.VITE_APP_SSE === 'false') {
  7. return;
  8. }
  9. url = url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID;
  10. const {
  11. data,
  12. error
  13. } = useEventSource(url, [], {
  14. autoReconnect: {
  15. retries: 10,
  16. delay: 3000,
  17. onFailed() {
  18. console.log('Failed to connect after 10 retries');
  19. }
  20. }
  21. });
  22. watch(error, () => {
  23. console.log('SSE connection error:', error.value);
  24. error.value = null;
  25. });
  26. watch(data, () => {
  27. if (!data.value) return;
  28. useNoticeStore().addNotice({
  29. message: data.value,
  30. read: false,
  31. time: new Date().toLocaleString()
  32. });
  33. ElNotification({
  34. title: '消息',
  35. message: data.value,
  36. type: 'success',
  37. duration: 3000
  38. });
  39. data.value = null;
  40. });
  41. };