2024-12-28 01:37:44 +00:00
|
|
|
import { OnInit, Injectable } from '@angular/core';
|
2024-10-17 08:48:15 +00:00
|
|
|
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
|
2025-01-08 21:50:18 +00:00
|
|
|
import { catchError, first, timeout } from 'rxjs/operators';
|
2024-10-17 08:48:15 +00:00
|
|
|
import { environment } from '../environments/environment';
|
2024-12-28 01:37:44 +00:00
|
|
|
import { Observable, throwError } from 'rxjs';
|
2024-10-17 08:48:15 +00:00
|
|
|
|
|
|
|
|
|
|
|
@Injectable({
|
|
|
|
providedIn: 'root'
|
|
|
|
})
|
|
|
|
export class HermesSocketService implements OnInit {
|
|
|
|
private socket: WebSocketSubject<any> | undefined = undefined
|
|
|
|
|
|
|
|
constructor() { }
|
|
|
|
|
|
|
|
ngOnInit(): void {
|
|
|
|
}
|
|
|
|
|
|
|
|
public connect(): void {
|
|
|
|
if (!this.socket || this.socket.closed) {
|
|
|
|
this.socket = this.getNewWebSocket();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-12-28 01:37:44 +00:00
|
|
|
public first(predicate: (data: any) => boolean): Observable<any>|null {
|
|
|
|
if (!this.socket || this.socket.closed)
|
|
|
|
return null;
|
|
|
|
|
|
|
|
return this.socket.pipe(timeout(3000), catchError((e) => throwError(() => 'No response after 3 seconds.')), first(predicate));
|
|
|
|
}
|
|
|
|
|
2024-10-17 08:48:15 +00:00
|
|
|
private getNewWebSocket() {
|
|
|
|
return webSocket({
|
2024-10-25 19:09:34 +00:00
|
|
|
url: environment.WSS_ENDPOINT
|
2024-10-17 08:48:15 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public sendMessage(msg: any) {
|
|
|
|
if (!this.socket || this.socket.closed)
|
2024-12-28 01:37:44 +00:00
|
|
|
return;
|
2024-10-17 08:48:15 +00:00
|
|
|
|
|
|
|
this.socket.next(msg);
|
|
|
|
}
|
|
|
|
|
|
|
|
public subscribe(subscriptions: any) {
|
|
|
|
if (!this.socket || this.socket.closed)
|
2024-12-28 01:37:44 +00:00
|
|
|
return;
|
2024-10-17 08:48:15 +00:00
|
|
|
|
|
|
|
return this.socket.subscribe(subscriptions);
|
|
|
|
}
|
|
|
|
|
|
|
|
public close() {
|
|
|
|
if (!this.socket || this.socket.closed)
|
2024-12-28 01:37:44 +00:00
|
|
|
return;
|
2024-10-17 08:48:15 +00:00
|
|
|
|
|
|
|
this.socket.complete();
|
|
|
|
}
|
|
|
|
}
|