1
1
import { EventBus } from '@/event-bus' ;
2
2
import { SIGNALR_CONFIG } from '../config' ;
3
- import { HubConnection , HubConnectionBuilder , HubConnectionState } from '@microsoft/signalr' ;
3
+ import { HubConnection , HubConnectionBuilder , HubConnectionState , LogLevel } from '@microsoft/signalr' ;
4
4
5
5
/**
6
6
* SignalR API abstraction layer communication.
@@ -19,15 +19,26 @@ class SignalRService {
19
19
return this . _signalRService || ( this . _signalRService = new this ( ) ) ;
20
20
}
21
21
22
- public startConnection ( ) : void {
23
- if ( this . _hubConnection . state === HubConnectionState . Disconnected ) {
24
- this . _hubConnection . start ( ) . catch ( ( e ) => console . error ( e ) ) ;
22
+ get connectionState ( ) : HubConnectionState {
23
+ return this . _hubConnection ?. state ?? HubConnectionState . Disconnected ;
24
+ }
25
+
26
+ public async startConnection ( ) : Promise < void > {
27
+ try {
28
+ await this . _hubConnection ?. start ( ) ;
29
+ console . assert ( this . connectionState === HubConnectionState . Connected ) ;
30
+ } catch ( e ) {
31
+ console . assert ( this . connectionState === HubConnectionState . Disconnected ) ;
32
+ console . error ( e ) ;
33
+ setTimeout ( ( ) => this . startConnection ( ) , 5000 ) ;
25
34
}
26
35
}
27
36
28
37
private createConnection ( ) : void {
29
38
this . _hubConnection = new HubConnectionBuilder ( )
30
39
. withUrl ( SIGNALR_CONFIG . baseUrl )
40
+ . withAutomaticReconnect ( )
41
+ . configureLogging ( LogLevel . Information )
31
42
. build ( ) ;
32
43
}
33
44
@@ -50,11 +61,13 @@ class SignalRService {
50
61
this . hubToastMessage ( 'A user has logged out' ) ;
51
62
} ) ;
52
63
53
- this . _hubConnection . on ( SIGNALR_CONFIG . events . closeConnections , ( reason : string ) => {
54
- this . _hubConnection . stop ( )
55
- . then ( ( ) => {
56
- this . hubToastMessage ( `Hub closed (${ reason } )` ) ;
57
- } ) ;
64
+ this . _hubConnection . on ( SIGNALR_CONFIG . events . closeConnections , async ( reason : string ) => {
65
+ try {
66
+ await this . _hubConnection . stop ( ) ;
67
+ this . hubToastMessage ( `Hub closed (${ reason } )` ) ;
68
+ } catch ( e ) {
69
+ console . error ( e ) ;
70
+ }
58
71
} ) ;
59
72
}
60
73
}
0 commit comments