You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.5 KiB
59 lines
1.5 KiB
import { Injectable } from '@angular/core';
|
|
import { environment } from '../../environments/environment';
|
|
import {HttpClient} from '@angular/common/http';
|
|
import {Observable} from 'rxjs';
|
|
import ApiResponse from '../structures/ApiResponse';
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class ApiService {
|
|
protected baseEndpoint: string = environment.backendBase;
|
|
|
|
constructor(
|
|
protected http: HttpClient,
|
|
) { }
|
|
|
|
public get(endpoint, params = {}): Observable<ApiResponse> {
|
|
return this.request(endpoint, params, 'get');
|
|
}
|
|
|
|
public post(endpoint, body = {}): Observable<ApiResponse> {
|
|
return this.request(endpoint, body, 'post');
|
|
}
|
|
|
|
public request(endpoint, params = {}, method: 'get'|'post' = 'get'): Observable<ApiResponse> {
|
|
return new Observable<ApiResponse>(sub => {
|
|
let data: any = {}
|
|
if ( method === 'get' ) {
|
|
data.params = params;
|
|
} else {
|
|
data = params;
|
|
}
|
|
|
|
this.http[method](this._build_url(endpoint), data).subscribe({
|
|
next: (response: any) => {
|
|
sub.next(new ApiResponse(response));
|
|
},
|
|
error: (err) => {
|
|
const response = {
|
|
status: err.status,
|
|
message: err.message,
|
|
data: err.error,
|
|
};
|
|
|
|
sub.next(new ApiResponse(response));
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
public _build_url(endpoint) {
|
|
if ( !endpoint.startsWith('/') ) {
|
|
endpoint = `/${endpoint}`;
|
|
}
|
|
|
|
return `${this.baseEndpoint.endsWith('/') ? this.baseEndpoint.slice(0, -1) : this.baseEndpoint}${endpoint}`;
|
|
}
|
|
}
|