import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/internal/Observable'; import { catchError } from 'rxjs/operators'; import { ErrorLoggerService } from '../core/error-logger.service'; import { ProductSku } from '../core/product-sku'; 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(): Observable { return this.http .get(`${url}/list`) .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; } getIngredientDetails( id: string, startDate: string | null, finishDate: string | null, ): Observable { const getUrl: string = `${url}/ingredient-details/${id}`; const options = { params: new HttpParams(), }; if (startDate !== null) { options.params = options.params.set('s', startDate); } if (finishDate !== null) { options.params = options.params.set('f', finishDate); } return this.http .get(getUrl, options) .pipe( catchError(this.log.handleError(serviceName, `get id=${id}`)), ) as Observable; } }