allerta-vvf/frontend/src/app/_services/api-client.service.ts

67 lines
1.8 KiB
TypeScript
Raw Normal View History

2021-12-22 23:06:58 +01:00
import { Injectable } from '@angular/core';
2022-01-07 16:41:09 +01:00
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
2021-12-22 23:06:58 +01:00
@Injectable({
providedIn: 'root'
})
export class ApiClientService {
2021-12-24 17:54:17 +01:00
private apiRoot = 'api/';
2021-12-22 23:06:58 +01:00
constructor(private http: HttpClient) { }
2021-12-22 23:06:58 +01:00
public apiEndpoint(endpoint: string): string {
2022-01-07 16:41:09 +01:00
if(endpoint.startsWith('https')) {
return endpoint;
}
2021-12-22 23:06:58 +01:00
return this.apiRoot + endpoint;
}
2021-12-29 14:23:45 +01:00
public dataToParams(data: any): string {
return Object.keys(data).reduce(function (params, key) {
if(typeof data[key] === 'object') {
data[key] = JSON.stringify(data[key]);
}
params.set(key, data[key]);
return params;
}, new URLSearchParams()).toString();
}
2022-01-07 16:41:09 +01:00
public get(endpoint: string, data: any = {}) {
2021-12-22 23:06:58 +01:00
return new Promise<any>((resolve, reject) => {
2022-01-07 16:41:09 +01:00
this.http.get(this.apiEndpoint(endpoint), {
params: new HttpParams({ fromObject: data })
}).subscribe({
next: (v) => resolve(v),
error: (e) => reject(e)
2021-12-22 23:06:58 +01:00
});
});
}
public post(endpoint: string, data: any = {}) {
2021-12-22 23:06:58 +01:00
return new Promise<any>((resolve, reject) => {
this.http.post(this.apiEndpoint(endpoint), this.dataToParams(data)).subscribe({
next: (v) => resolve(v),
error: (e) => reject(e)
2021-12-22 23:06:58 +01:00
});
});
}
public put(endpoint: string, data: any = {}) {
2021-12-22 23:06:58 +01:00
return new Promise<any>((resolve, reject) => {
this.http.put(this.apiEndpoint(endpoint), this.dataToParams(data)).subscribe({
next: (v) => resolve(v),
error: (e) => reject(e)
2021-12-22 23:06:58 +01:00
});
});
}
public delete(endpoint: string) {
return new Promise<any>((resolve, reject) => {
this.http.delete(this.apiEndpoint(endpoint)).subscribe({
next: (v) => resolve(v),
error: (e) => reject(e)
2021-12-22 23:06:58 +01:00
});
});
}
2022-01-04 00:08:13 +01:00
}