summaryrefslogtreecommitdiff
path: root/recipeBuddy/src/app/REST_service/backend.service.ts
blob: 1a2d933785794c53a4656de4b1bde49ba2166539 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { Injectable } from '@angular/core'
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { Observable, throwError } from 'rxjs'
import { retry, catchError, map } from 'rxjs/operators'
import { Recipe } from '../DataModels/recipe'


export interface Status {
	Code: number;
	Msg: string;
}
export interface MsgList {
	Status: Status;
	Data: number[];
}

export interface Msg {
	Status: Status;
	Data: Recipe;
}


@Injectable({ providedIn: 'root' })

/* BackendService class based on tutorial at:
 * <https://www.positronx.io/angular-8-httpclient-http-tutorial-build-consume-restful-api/>
 */
export class BackendService {
	apiURL = 'http://api.recipebuddy.xyz:8888'

	constructor( private http: HttpClient)
	{
	}

	httpOptions = {headers: new HttpHeaders(
		{'Content-Type':'application/json'}
	)}


	getRecipes(): Observable<number[]>
	{
		return this.http.get<MsgList>(this.apiURL + '/recipes')
			.pipe (
				retry(1),
				map(msg => msg.Data),
				catchError(this.handleError)
			)
	}


	getRecipe(id): Observable<Recipe>
	{
		return this.http.get<Msg>(this.apiURL + '/recipes/' + id)
			.pipe (
				retry(1),
				map(msg => msg.Data),
				catchError(this.handleError)
			)
	}

	createRecipe(data): Observable<Recipe>
	{
		return this.http.post<Recipe>(this.apiURL + '/recipes',
			JSON.stringify(data), this.httpOptions)
	}

	updateRecipe(data): Observable<Recipe>
	{
		return this.http.put<Recipe>(this.apiURL + '/recipes/' + data.id,
			JSON.stringify(data), this.httpOptions)
	}

	deleteRecipe(id): Observable<Msg>
	{
		return this.http.delete<Msg>(this.apiURL + '/recipes/' + id)
			.pipe (
				retry(1),
				catchError(this.handleError)
			)
	}

	handleError(error) {
		let errMsg = '';
		if (error.error instanceof ErrorEvent) {
			errMsg = error.error.message;
		} else {
			errMsg = 'Error API';
		}
		console.log(errMsg)
		window.alert(errMsg)
		return throwError(errMsg);
	}
}