client.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  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 || '/') + 'sse')
  8. this.source.onmessage = (e: MessageEvent) => {
  9. this.handleMsg(JSON.parse(e.data))
  10. }
  11. this.source.onerror = () => {
  12. this.source?.close()
  13. this.source = undefined
  14. console.warn('SSE 连接关闭或出错')
  15. }
  16. }
  17. close() {
  18. this.source?.close()
  19. this.source = undefined
  20. }
  21. handleMsg(data: any) {
  22. if(data.type === 'command' && data.value === 'Re-login') {
  23. // 跳转前,保存原始地址
  24. const urlParam = new URLSearchParams(this.signinUrl)
  25. const state = urlParam.get('state')
  26. if (state) {
  27. setOriginalUrl(state, window.location.href)
  28. }
  29. // 重新登录,跳转到登录页面
  30. window.location.href = this.signinUrl.replace(/^https?:\/\/[^/]+/, '')
  31. }
  32. }
  33. }