import { inject, Injectable } from '@angular/core'; import { HermesClientService } from '../../hermes-client.service'; import EventService from './EventService'; import { map, Observable, of } from 'rxjs'; import { Connection } from '../models/connection'; @Injectable({ providedIn: 'root' }) export class ConnectionService { private readonly client = inject(HermesClientService); private readonly events = inject(EventService); private data: Connection[] = []; private loaded = false; create$: Observable | undefined; update$: Observable | undefined; delete$: Observable | undefined; constructor() { this.create$ = this.client.filterByRequestType('create_connection'); this.update$ = this.client.filterByRequestType('update_connection'); this.delete$ = this.client.filterByRequestType('delete_connection'); this.create$?.subscribe(d => { if (d.error) { return; } this.data.push(d.data); }); this.update$?.subscribe(d => { if (d.error) { return; } const connection = this.data.find(p => p.name == d.data.name); if (connection) { connection.type = d.data.type; connection.client_id = d.data.client_id; connection.access_token = d.data.access_token; connection.grant_type = d.data.grant_type; connection.scope = d.data.scope; connection.expires_at = d.data.expires_at; connection.default = d.data.default; } }); this.delete$?.subscribe(d => { if (d.error) { return; } this.data = this.data.filter(r => r.name != d.request.data.name); }); this.events.listen('tts_logoff', () => { this.data = []; this.loaded = false; }); } fetch() { if (this.loaded) { return of(this.data); } const $ = this.client.first(d => d.d.request.type == 'get_connections')!.pipe(map(d => d.d.data)); $.subscribe(d => { this.data = d; this.loaded = true; }); this.client.fetchConnections(); return $; } }