-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocketService.ts
More file actions
58 lines (46 loc) · 1.51 KB
/
Copy pathwebsocketService.ts
File metadata and controls
58 lines (46 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { io, Socket } from 'socket.io-client';
interface TransactionStatusUpdate {
hash: string;
status: 'pending' | 'confirming' | 'completed' | 'failed';
}
class WebSocketService {
private socket: Socket | null = null;
private readonly backendUrl: string;
constructor() {
this.backendUrl = process.env.REACT_APP_BACKEND_URL || 'http://localhost:3001';
}
public connect(): void {
if (!this.socket || !this.socket.connected) {
this.socket = io(this.backendUrl, {
transports: ['websocket'],
reconnectionAttempts: 5,
reconnectionDelay: 1000,
});
this.socket.on('connect', () => {
console.log('WebSocket connected:', this.socket?.id);
});
this.socket.on('disconnect', (reason) => {
console.log('WebSocket disconnected:', reason);
});
this.socket.on('connect_error', (error) => {
console.error('WebSocket connection error:', error);
});
}
}
public disconnect(): void {
if (this.socket) {
this.socket.disconnect();
this.socket = null;
}
}
public onTransactionStatusUpdate(callback: (update: TransactionStatusUpdate) => void): void {
this.socket?.on('transactionStatusUpdate', callback);
}
public offTransactionStatusUpdate(callback: (update: TransactionStatusUpdate) => void): void {
this.socket?.off('transactionStatusUpdate', callback);
}
public isConnected(): boolean {
return this.socket?.connected || false;
}
}
export const websocketService = new WebSocketService();