import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  private formatErrors(error: any) {
    return throwError(error.error);
  }

  get(path: string, httpOptions: any): Observable<any> {
    return this.http.get(`${path}`, httpOptions)
      .pipe(catchError(this.formatErrors));
  }

  put(path: string, body: Object = {}, httpOptions: any): Observable<any> {
    return this.http.put(
      `${path}`,
      JSON.stringify(body)
    ).pipe(catchError(this.formatErrors));
  }

  post(path: string, body: Object = {}, httpOptions: any, isFileUpload : boolean = false): Observable<any> {
    var params = isFileUpload ? body : JSON.stringify(body);
    return this.http.post(
      `${path}`,
      params, httpOptions
    ).pipe(catchError(this.formatErrors));
  }

  delete(path): Observable<any> {
    return this.http.delete(
      `${path}`
    ).pipe(catchError(this.formatErrors));
  }
}
