hermes-web-angular/src/app/hermes-socket.service.ts

63 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-12-28 01:37:44 +00:00
import { OnInit, Injectable } from '@angular/core';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
import { catchError, filter, first, timeout } from 'rxjs/operators';
import { environment } from '../environments/environment';
2024-12-28 01:37:44 +00:00
import { Observable, throwError } from 'rxjs';
@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();
}
}
public first(predicate: (data: any) => boolean): Observable<any> {
2024-12-28 01:37:44 +00:00
if (!this.socket || this.socket.closed)
return new Observable().pipe(timeout(3000), catchError((e) => throwError(() => 'No response after 3 seconds.')));
2024-12-28 01:37:44 +00:00
return this.socket.pipe(timeout(3000), catchError((e) => throwError(() => 'No response after 3 seconds.')), first(predicate));
}
private getNewWebSocket(): WebSocketSubject<any> {
return webSocket({
2024-10-25 19:09:34 +00:00
url: environment.WSS_ENDPOINT
});
}
public sendMessage(msg: any): void {
if (!this.socket || this.socket.closed)
2024-12-28 01:37:44 +00:00
return;
this.socket.next(msg);
}
public get$(): Observable<any>|undefined {
return this.socket?.asObservable();
}
public subscribe(subscriptions: any) {
if (!this.socket || this.socket.closed)
2024-12-28 01:37:44 +00:00
return;
return this.socket.subscribe(subscriptions);
}
public close() {
if (!this.socket || this.socket.closed)
2024-12-28 01:37:44 +00:00
return;
this.socket.complete();
}
}