import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, of as observableOf } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { ErrorLoggerService } from '../core/error-logger.service'; import { Recipe } from './recipe'; const url = '/api/recipes'; const serviceName = 'RecipeService'; @Injectable({ providedIn: 'root' }) export class RecipeService { constructor( private http: HttpClient, private log: ErrorLoggerService, ) {} get(id: string | null): Observable { const getUrl: string = id === null ? `${url}` : `${url}/${id}`; return this.http .get(getUrl) .pipe(catchError(this.log.handleError(serviceName, `get id=${id}`))) as Observable; } list(periodId: string | null): Observable { if (periodId === null) { return observableOf([]); } return this.http .get(`${url}/list`, { params: new HttpParams().set('p', periodId) }) .pipe(catchError(this.log.handleError(serviceName, 'getList'))) as Observable; } save(recipe: Recipe): Observable { return this.http .post(`${url}`, recipe) .pipe(catchError(this.log.handleError(serviceName, 'save'))) as Observable; } update(recipe: Recipe): Observable { return this.http .put(`${url}/${recipe.id}`, recipe) .pipe(catchError(this.log.handleError(serviceName, 'update'))) as Observable; } saveOrUpdate(recipe: Recipe): Observable { if (!recipe.id) { return this.save(recipe); } return this.update(recipe); } delete(id: string): Observable { return this.http .delete(`${url}/${id}`) .pipe(catchError(this.log.handleError(serviceName, 'delete'))) as Observable; } }