| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- import { setOriginalUrl } from './stateMap'
- export default class EventClient {
- private source : EventSource | undefined = undefined
- private readonly signinUrl: string
- constructor(signinUrl: string) {
- this.signinUrl = signinUrl
- this.source = new EventSource((import.meta.env.BASE_URL || '/') + 'api/sse')
- this.source.onmessage = (e: MessageEvent) => {
- this.handleMsg(JSON.parse(e.data))
- }
- this.source.onerror = (e: Event) => {
- this.source?.close()
- this.source = undefined
- console.warn("SSE 连接关闭或出错:", e)
- // 如果是 MessageEvent 或 ErrorEvent,可尝试打印更多细节
- if (e instanceof ErrorEvent) {
- console.error("错误详情:", e.message, e.filename, e.lineno)
- } else if (e instanceof MessageEvent) {
- console.error("消息内容:", e.data)
- } else {
- // 一些浏览器可能用 `EventSource.readyState` 表示连接状态
- console.warn("EventSource 状态:", this.source?.readyState)
- }
- }
- }
- close() {
- this.source?.close()
- this.source = undefined
- }
- handleMsg(data: any) {
- if(data.type === 'command' && data.value === 'Re-login') {
- // 跳转前,保存原始地址
- const urlParam = new URLSearchParams(this.signinUrl)
- const state = urlParam.get('state')
- if (state) {
- setOriginalUrl(state, window.location.href)
- }
-
- // 重新登录,跳转到登录页面
- window.location.href = this.signinUrl.replace(/^https?:\/\/[^/]+/, '')
- }
- }
- }
|