Tools/src/main/angular/src/app/api/common/api.service.ts

76 lines
2.8 KiB
TypeScript

import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {map, Subscription} from "rxjs";
import {FromJson, getApiUrl, Next} from "./types";
import {Page} from "./Page";
import {StompService} from "@stomp/ng2-stompjs";
@Injectable({
providedIn: 'root',
})
export class ApiService {
private _websocketError: boolean = false;
get websocketError(): boolean {
return this._websocketError;
}
constructor(
private readonly http: HttpClient,
private readonly stompService: StompService,
) {
stompService.connected$.subscribe(() => this._websocketError = false);
stompService.webSocketErrors$.subscribe(() => this._websocketError = true);
}
connected(next: Next<void>): Subscription {
return this.stompService.connected$.subscribe(_ => next());
}
subscribe<T>(topic: any[], fromJson: FromJson<T>, next: Next<T>): Subscription {
console.info("WEBSOCKET SUBSCRIBE", topic)
return this.stompService
.subscribe(topic.join("/"))
.pipe(
map(message => message.body),
map(b => JSON.parse(b)),
map(j => fromJson(j)),
)
.subscribe(next);
}
getNone<T>(path: any[], next?: Next<void>): Subscription {
return this.http.get<void>(getApiUrl('http', path), {withCredentials: true}).subscribe(next);
}
getString(path: any[], next: Next<string>): Subscription {
return this.http.get(getApiUrl('http', path), {responseType: "text", withCredentials: true}).subscribe(next);
}
getSingle<T>(path: any[], fromJson: FromJson<T>, next?: Next<T>): Subscription {
return this.http.get<any>(getApiUrl('http', path), {withCredentials: true}).pipe(map(fromJson)).subscribe(next);
}
getList<T>(path: any[], fromJson: FromJson<T>, next: Next<T[]> | undefined = undefined): Subscription {
return this.http.get<any[]>(getApiUrl('http', path), {withCredentials: true}).pipe(map(list => list.map(fromJson))).subscribe(next);
}
postNone(path: any[], data: any, next?: Next<void>): Subscription {
return this.http.post<void>(getApiUrl('http', path), data, {withCredentials: true}).subscribe(next);
}
postSingle<T>(path: any[], data: any, fromJson: FromJson<T>, next?: Next<T>): Subscription {
return this.http.post<any>(getApiUrl('http', path), data, {withCredentials: true}).pipe(map(fromJson)).subscribe(next);
}
postPage<T>(path: any[], data: any, fromJson: FromJson<T>, next: Next<Page<T>> | undefined = undefined): Subscription {
return this.http.post<any>(getApiUrl('http', path), data, {withCredentials: true}).pipe(map(Page.fromJson(fromJson))).subscribe(next);
}
postList<T>(path: any[], data: any, fromJson: FromJson<T>, next: Next<T[]> | undefined = undefined): Subscription {
return this.http.post<any[]>(getApiUrl('http', path), data, {withCredentials: true}).pipe(map(list => list.map(fromJson))).subscribe(next);
}
}