import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/internal/Observable'; import { catchError } from 'rxjs/operators'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { Modifier } from '../core/modifier'; import { ErrorLoggerService } from '../core/error-logger.service'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; const url = '/v1/modifiers'; const serviceName = 'ModifierService'; @Injectable({providedIn: 'root'}) export class ModifierService { constructor(private http: HttpClient, private log: ErrorLoggerService) { } get(id: string): Observable { const getUrl: string = (id === null) ? `${url}/new` : `${url}/${id}`; return >this.http.get(getUrl) .pipe( catchError(this.log.handleError(serviceName, `get id=${id}`)) ); } list(): Observable { const options = {params: new HttpParams().set('l', '')}; return >this.http.get(url, options) .pipe( catchError(this.log.handleError(serviceName, 'getList')) ); } save(modifier: Modifier): Observable { return >this.http.post(`${url}/new`, modifier, httpOptions) .pipe( catchError(this.log.handleError(serviceName, 'save')) ); } update(modifier: Modifier): Observable { return >this.http.put(`${url}/${modifier.id}`, modifier, httpOptions) .pipe( catchError(this.log.handleError(serviceName, 'update')) ); } updateSortOrder(list: Modifier[]): Observable { return >this.http.post(url, list, httpOptions) .pipe( catchError(this.log.handleError(serviceName, 'updateSortOrder')) ); } saveOrUpdate(modifier: Modifier): Observable { if (!modifier.id) { return this.save(modifier); } else { return this.update(modifier); } } delete(id: string): Observable { return >this.http.delete(`${url}/${id}`, httpOptions) .pipe( catchError(this.log.handleError(serviceName, 'delete')) ); } autocomplete(term: string): Observable { const options = {params: new HttpParams().set('t', term)}; return >this.http.get(url, options) .pipe( catchError(this.log.handleError(serviceName, 'autocomplete')) ); } balance(id: string, date: string): Observable { const options = {params: new HttpParams().set('b', 'true').set('d', date)}; return >this.http.get(`${url}/${id}`, options) .pipe( catchError(this.log.handleError(serviceName, 'balance')) ); } }