import type { LogFunc } from '../interface/common'; import { LogType } from '../interface/common'; import type { SocketMessageInterface, WebSocketLifeCycle } from '../interface/socket'; export default class EventManager { constructor(private _socket: WebSocket, private _lifeCycle?: WebSocketLifeCycle, private _log?: LogFunc) { } public setupEventHandlers(): void { this._socket.onopen = this._onOpen.bind(this); this._socket.onclose = this._onClose.bind(this); this._socket.onerror = this._onError.bind(this); this._socket.onmessage = this._onMessage.bind(this); } private _onOpen(ev: Event): void { this._log?.(LogType.info, `[socket] open ws success url: ${this._socket.url}`); this._lifeCycle?.onOpen?.(ev, this._socket); } private _onClose(ev: CloseEvent): void { // ... existing logic this._lifeCycle?.onClose?.(ev, this._socket) if (ev.code === 1000) { this._log?.(LogType.info, '[socket] close normally'); return; } this._log?.( LogType.info, '[socket] close abnormally, try to reconnect' ); } private _onError(ev: Event): void { const event: CloseEvent = new CloseEvent('close', { ...ev }); this._lifeCycle?.onError?.(event) } private _onMessage(message: MessageEvent): void { try { const msgData = JSON.parse(message.data) as SocketMessageInterface; const { type } = msgData; this._log?.(LogType.info, `[socket] received type: ${type}`, msgData); this._lifeCycle?.onMessage?.(msgData); } catch (error) { this._log?.(LogType.error, '[socket] received msg error: ', error); } } }