You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Global-sales/src/lib/websocketLib2.js

68 lines
1.7 KiB
JavaScript

// websocketLib.js
import { WebSocketSubject } from 'rxjs/webSocket';
import { retryWhen, delay, take, catchError } from 'rxjs/operators';
class WebSocketLib {
constructor(url, authToken, protocol) {
this.url = url;
this.authToken = authToken;
this.protocol = protocol;
}
connect() {
this.socket$ = new WebSocketSubject({
url: this.url,
protocol: this.protocol, // Use protocol for message type
openObserver: {
next: () => {
console.log('Connection established');
// Send authentication message as soon as connection is established
this.socket$.next({ event: 'authenticate', token: this.authToken });
},
},
closeObserver: {
next: () => {
console.log('Connection closed');
},
},
});
this.socket$
.pipe(
retryWhen(errors =>
errors.pipe(
delay(1000), // Retry connection every 1 second
take(10), // Maximum of 10 retries
catchError(error => new Error(`Failed to reconnect: ${error}`)) // Throw error after 10 failed retries
)
)
)
.subscribe(
msg => console.log('Received message:', msg),
err => console.error('Received error:', err),
() => console.log('Connection closed')
);
}
sendMessage(message) {
if (!this.socket$) {
console.error('Must connect to WebSocket server before sending a message');
return;
}
this.socket$.next({ type: 'message', content: message });
}
disconnect() {
if (!this.socket$) {
console.error('Must connect to WebSocket server before disconnecting');
return;
}
this.socket$.complete();
this.socket$ = null;
}
}
export default WebSocketLib;