refactor(frontend): Migrate state to Tanstack Query + signals (#117)
* refactor(frontend): migrate state to TanStack Query and signals * fix(frontend): keep book cache in sync after patches
This commit is contained in:
@@ -1,33 +1,43 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {computed, inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {BehaviorSubject, Observable} from 'rxjs';
|
||||
import {distinctUntilChanged, map} from 'rxjs/operators';
|
||||
import {lastValueFrom} from 'rxjs';
|
||||
import {RxStompService} from '../../../shared/websocket/rx-stomp.service';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
const LIBRARY_HEALTH_QUERY_KEY = ['libraryHealth'] as const;
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class LibraryHealthService {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries/health`;
|
||||
private http = inject(HttpClient);
|
||||
private rxStompService = inject(RxStompService);
|
||||
private queryClient = inject(QueryClient);
|
||||
|
||||
private healthSubject = new BehaviorSubject<Record<number, boolean>>({});
|
||||
private healthQuery = injectQuery(() => ({
|
||||
...this.getHealthQueryOptions(),
|
||||
enabled: false, // manually triggered via initialize()
|
||||
}));
|
||||
|
||||
health = computed(() => this.healthQuery.data() ?? {});
|
||||
|
||||
private getHealthQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: LIBRARY_HEALTH_QUERY_KEY,
|
||||
queryFn: () => lastValueFrom(this.http.get<Record<number, boolean>>(this.url))
|
||||
});
|
||||
}
|
||||
|
||||
initialize(): void {
|
||||
this.http.get<Record<number, boolean>>(this.url).subscribe(health => {
|
||||
this.healthSubject.next(health);
|
||||
});
|
||||
void this.queryClient.fetchQuery(this.getHealthQueryOptions());
|
||||
|
||||
this.rxStompService.watch('/topic/library-health').subscribe(msg => {
|
||||
const payload = JSON.parse(msg.body);
|
||||
this.healthSubject.next(payload.libraryHealth);
|
||||
this.queryClient.setQueryData(LIBRARY_HEALTH_QUERY_KEY, payload.libraryHealth);
|
||||
});
|
||||
}
|
||||
|
||||
isUnhealthy$(libraryId: number): Observable<boolean> {
|
||||
return this.healthSubject.pipe(
|
||||
map(health => health[libraryId] === false),
|
||||
distinctUntilChanged()
|
||||
);
|
||||
isUnhealthy(libraryId: number): boolean {
|
||||
return this.health()[libraryId] === false;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user