@@ -61,6 +61,9 @@ export type WebSocketServiceOptions = {
61
61
62
62
/** Request timeout in milliseconds (default: 30000) */
63
63
requestTimeout ?: number ;
64
+
65
+ /** Optional callback to determine if connection should be enabled (default: always enabled) */
66
+ enabledCallback ?: ( ) => boolean ;
64
67
} ;
65
68
66
69
/**
@@ -216,7 +219,9 @@ export class WebSocketService {
216
219
217
220
readonly #messenger: WebSocketServiceMessenger ;
218
221
219
- readonly #options: Required < Omit < WebSocketServiceOptions , 'messenger' > > ;
222
+ readonly #options: Required < Omit < WebSocketServiceOptions , 'messenger' | 'enabledCallback' > > ;
223
+
224
+ readonly #enabledCallback: ( ( ) => boolean ) | undefined ;
220
225
221
226
#ws: WebSocket | undefined ;
222
227
@@ -269,6 +274,7 @@ export class WebSocketService {
269
274
*/
270
275
constructor ( options : WebSocketServiceOptions ) {
271
276
this . #messenger = options . messenger ;
277
+ this . #enabledCallback = options . enabledCallback ;
272
278
273
279
this . #options = {
274
280
url : options . url ,
@@ -291,6 +297,12 @@ export class WebSocketService {
291
297
* @returns Promise that resolves when connection is established
292
298
*/
293
299
async connect ( ) : Promise < void > {
300
+ // Check if connection is enabled via callback
301
+ if ( this . #enabledCallback && ! this . #enabledCallback( ) ) {
302
+ console . log ( `[${ SERVICE_NAME } ] Connection disabled by enabledCallback - skipping connect` ) ;
303
+ return ;
304
+ }
305
+
294
306
// If already connected, return immediately
295
307
if ( this . #state === WebSocketState . CONNECTED ) {
296
308
return ;
@@ -1045,6 +1057,12 @@ export class WebSocketService {
1045
1057
) ;
1046
1058
1047
1059
this . #reconnectTimer = setTimeout ( ( ) => {
1060
+ // Check if connection is still enabled before reconnecting
1061
+ if ( this . #enabledCallback && ! this . #enabledCallback( ) ) {
1062
+ console . log ( `[${ SERVICE_NAME } ] Reconnection disabled by enabledCallback - skipping attempt #${ this . #reconnectAttempts} ` ) ;
1063
+ return ;
1064
+ }
1065
+
1048
1066
console . log (
1049
1067
`🔄 ${ delay } ms delay elapsed - starting reconnection attempt #${ this . #reconnectAttempts} ...` ,
1050
1068
) ;
0 commit comments