sse.ts 1018 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 { data, error } = useEventSource(url, [], {
  11. autoReconnect: {
  12. retries: 10,
  13. delay: 3000,
  14. onFailed() {
  15. console.log('Failed to connect after 10 retries');
  16. }
  17. }
  18. });
  19. watch(error, () => {
  20. console.log('SSE connection error:', error.value);
  21. error.value = null;
  22. });
  23. watch(data, () => {
  24. if (!data.value) return;
  25. useNoticeStore().addNotice({
  26. message: data.value,
  27. read: false,
  28. time: new Date().toLocaleString()
  29. });
  30. ElNotification({
  31. title: '消息',
  32. message: data.value,
  33. type: 'success',
  34. duration: 3000
  35. });
  36. data.value = null;
  37. });
  38. };