All files / lib/services/websocket websocket-api.service.ts

100% Statements 10/10
100% Branches 0/0
100% Functions 6/6
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42                            2x 5x   5x   5x     3x   1x     1x 1x           1x       1x      
import { DestroyRef, inject, Injectable } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { WebSocketSubject } from 'rxjs/webSocket';
 
import { type IWebsocketRequestEvent, type IWebsocketResponseEvent, WS_CONFIG } from '../../diagnostics.interface';
 
/**
 * Websocket API Service.
 */
@Injectable({
  providedIn: 'root',
})
export class AppWebsocketApiService {
  private readonly destroyRef = inject(DestroyRef);
 
  private readonly wsConfig = inject(WS_CONFIG);
 
  private readonly wsSubject = new WebSocketSubject<IWebsocketRequestEvent>(this.wsConfig);
 
  public connect<T = unknown>() {
    return this.wsSubject.pipe(
      takeUntilDestroyed(this.destroyRef),
      map(event => event as IWebsocketResponseEvent<T>),
      catchError((error: Error) => {
        // eslint-disable-next-line no-console -- this is needed so that websocket erros are reported to console
        console.error('error', error);
        return of({ event: 'error.message' } as IWebsocketResponseEvent<T>);
      }),
    );
  }
 
  public startDiagEvents() {
    this.wsSubject.next({ event: 'start-diag' });
  }
 
  public stopDiagEvents() {
    this.wsSubject.next({ event: 'stop-diag' });
  }
}