McManager/src/main/angular/src/app/crud/ApiService.ts

56 lines
1.9 KiB
TypeScript

import {HttpClient} from "@angular/common/http";
import {FromJson, Next, url} from "./CrudHelpers";
import {filter, map, Subscription} from "rxjs";
import {Injectable} from '@angular/core';
import {RxStompService} from './rx-stomp.service';
import {RxStompState} from '@stomp/rx-stomp';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(
readonly http: HttpClient,
readonly stomp: RxStompService,
) {
}
getNone<T>(path: any[], next?: Next<void>): void {
this.http.get<void>(url('http', path)).subscribe(next);
}
getSingle<T>(path: any[], fromJson: FromJson<T>, next?: Next<T>): void {
this.http.get<any>(url('http', path)).pipe(map(fromJson)).subscribe(next);
}
getList<T>(path: any[], fromJson: FromJson<T>, next?: Next<T[]>): void {
this.http.get<any[]>(url('http', path)).pipe(map(list => list.map(fromJson))).subscribe(next);
}
postNone<T>(path: any[], data: any, next?: Next<void>): void {
this.http.post<void>(url('http', path), data).subscribe(next);
}
postSingle<T>(path: any[], data: any, fromJson: FromJson<T>, next?: Next<T>): void {
this.http.post<any>(url('http', path), data).pipe(map(fromJson)).subscribe(next);
}
postList<T>(path: any[], data: any, fromJson: FromJson<T>, next?: Next<T[]>): void {
this.http.post<any[]>(url('http', path), data).pipe(map(list => list.map(fromJson))).subscribe(next);
}
onConnect(next: Next<void>): Subscription {
return this.stomp.connectionState$.pipe(filter(state => state === RxStompState.OPEN)).subscribe(() => next());
}
onDisconnect(next: Next<void>): Subscription {
return this.stomp.connectionState$.pipe(filter(state => state === RxStompState.CLOSED)).subscribe(() => next());
}
subscribe<T>(path: any[], fromJson: FromJson<T>, next: Next<T>): Subscription {
return this.stomp.watch([...path].join('/')).pipe(map(m => fromJson(JSON.parse(m.body)))).subscribe(next);
}
}