import { io, Socket } from 'socket.io-client'; import { EventBus } from './EventBus'; export class WebSocketService { private socket: Socket | null = null; private eventBus: EventBus; private apiBaseUrl: string; constructor(eventBus: EventBus, apiBaseUrl: string) { this.eventBus = eventBus; this.apiBaseUrl = apiBaseUrl; } /** * Подключается к WebSocket серверу */ connect(): void { if (this.socket?.connected) { console.log('WebSocket уже подключен'); return; } // Извлекаем базовый URL без /api const wsUrl = this.apiBaseUrl.replace('/api', ''); this.socket = io(wsUrl, { transports: ['websocket', 'polling'], reconnection: true, reconnectionDelay: 1000, reconnectionDelayMax: 5000, reconnectionAttempts: 5 }); this.setupEventHandlers(); } /** * Настраивает обработчики WebSocket событий */ private setupEventHandlers(): void { if (!this.socket) return; this.socket.on('connect', () => { console.log('✅ WebSocket подключен'); }); this.socket.on('disconnect', (reason) => { console.log('❌ WebSocket отключен:', reason); }); this.socket.on('connect_error', (error) => { console.error('Ошибка подключения WebSocket:', error); }); // ----------------------------------------------- Title Update Events --------------------------------------------------------------- this.socket.on('graph_title_updated', (data: { graph_id: string; title: string }) => { console.log('📊 Получено обновление заголовка графа:', data); this.eventBus.emit('ws-graph-title-updated', data); }); this.socket.on('node_title_updated', (data: { graph_id: string; node_id: string; title: string }) => { console.log('📝 Получено обновление заголовка узла:', data); this.eventBus.emit('ws-node-title-updated', data); }); } /** * Отключается от WebSocket сервера */ disconnect(): void { if (this.socket) { this.socket.disconnect(); this.socket = null; console.log('WebSocket отключен'); } } /** * Проверяет статус подключения */ isConnected(): boolean { return this.socket?.connected ?? false; } }