Files
brewman/overlord/src/app/recipe/recipe.service.ts
T
2023-07-23 09:01:18 +05:30

61 lines
1.8 KiB
TypeScript

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<Recipe> {
const getUrl: string = id === null ? `${url}` : `${url}/${id}`;
return this.http
.get<Recipe>(getUrl)
.pipe(catchError(this.log.handleError(serviceName, `get id=${id}`))) as Observable<Recipe>;
}
list(periodId: string | null): Observable<Recipe[]> {
if (periodId === null) {
return observableOf([]);
}
return this.http
.get<Recipe[]>(`${url}/list`, { params: new HttpParams().set('p', periodId) })
.pipe(catchError(this.log.handleError(serviceName, 'getList'))) as Observable<Recipe[]>;
}
save(recipe: Recipe): Observable<Recipe> {
return this.http
.post<Recipe>(`${url}`, recipe)
.pipe(catchError(this.log.handleError(serviceName, 'save'))) as Observable<Recipe>;
}
update(recipe: Recipe): Observable<Recipe> {
return this.http
.put<Recipe>(`${url}/${recipe.id}`, recipe)
.pipe(catchError(this.log.handleError(serviceName, 'update'))) as Observable<Recipe>;
}
saveOrUpdate(recipe: Recipe): Observable<Recipe> {
if (!recipe.id) {
return this.save(recipe);
}
return this.update(recipe);
}
delete(id: string): Observable<Recipe> {
return this.http
.delete<Recipe>(`${url}/${id}`)
.pipe(catchError(this.log.handleError(serviceName, 'delete'))) as Observable<Recipe>;
}
}