| | |
| | | import type { AxiosRequestConfig } from 'axios'; |
| | | import { EventSourcePolyfill } from 'event-source-polyfill'; |
| | | import { accessSessionKey } from '../request'; |
| | | import { SESSION_KEY } from '../request'; |
| | | import { Local } from '../storage'; |
| | |
| | | this.options = { |
| | | retryDelay: 1000, |
| | | autoReconnect: true, |
| | | timeout: 24 * 60 * 60 * 1000, |
| | | timeout: 3000, |
| | | headers: { |
| | | [SESSION_KEY]: Local.get(accessSessionKey), |
| | | }, |
| | |
| | | |
| | | // 创建 AbortController 用于超时控制 |
| | | // this.abortController = new AbortController(); |
| | | |
| | | // 创建 EventSource 并添加 headers |
| | | this.eventSource = new EventSourcePolyfill(fullUrl, { |
| | | headers: this.options.headers, |
| | | heartbeatTimeout: this.options.timeout, |
| | | |
| | | }); |
| | | this.eventSource = new EventSource(fullUrl); |
| | | |
| | | // 绑定事件处理 |
| | | this.bindEvents(); |
| | | } catch (error) { |
| | | console.log('catch error'); |
| | | await this.debounceHandleError.call(this, error); |
| | | } |
| | | } |
| | | |
| | |
| | | }; |
| | | |
| | | this.eventSource.onerror = async (error) => { |
| | | console.log('on error'); |
| | | |
| | | await this.debounceHandleError.call(this, error); |
| | | }; |
| | | } |
| | | |
| | |
| | | * 错误处理 |
| | | */ |
| | | private async handleError(error: any): Promise<void> { |
| | | console.log('🚀 ~ error:', error); |
| | | this.callbacks.onError?.(error); |
| | | if (this.options.autoReconnect) { |
| | | this.callbacks.onRetry?.(); |
| | |
| | | } |
| | | } |
| | | |
| | | private debounceHandleError = debounce((error: any) => { |
| | | this.handleError(error); |
| | | }, 500); |
| | | |
| | | |
| | | /** |
| | | * 断开连接 |