client.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { setOriginalUrl } from './stateMap'
  2. export default class EventClient {
  3. private source : EventSource | undefined = undefined
  4. private readonly signinUrl: string
  5. constructor(signinUrl: string) {
  6. this.signinUrl = signinUrl
  7. this.source = new EventSource((import.meta.env.BASE_URL || '/') + 'api/sse')
  8. this.source.onmessage = (e: MessageEvent) => {
  9. this.handleMsg(JSON.parse(e.data))
  10. }
  11. this.source.onerror = (e: Event) => {
  12. this.source?.close()
  13. this.source = undefined
  14. console.warn("SSE 连接关闭或出错:", e)
  15. // 如果是 MessageEvent 或 ErrorEvent,可尝试打印更多细节
  16. if (e instanceof ErrorEvent) {
  17. console.error("错误详情:", e.message, e.filename, e.lineno)
  18. } else if (e instanceof MessageEvent) {
  19. console.error("消息内容:", e.data)
  20. } else {
  21. // 一些浏览器可能用 `EventSource.readyState` 表示连接状态
  22. console.warn("EventSource 状态:", this.source?.readyState)
  23. }
  24. }
  25. }
  26. close() {
  27. this.source?.close()
  28. this.source = undefined
  29. }
  30. handleMsg(data: any) {
  31. if(data.type === 'command' && data.value === 'Re-login') {
  32. // 跳转前,保存原始地址
  33. const urlParam = new URLSearchParams(this.signinUrl)
  34. const state = urlParam.get('state')
  35. if (state) {
  36. setOriginalUrl(state, window.location.href)
  37. }
  38. // 重新登录,跳转到登录页面
  39. window.location.href = this.signinUrl.replace(/^https?:\/\/[^/]+/, '')
  40. }
  41. }
  42. }