-
Notifications
You must be signed in to change notification settings - Fork 3
/
api-helper.service.ts
107 lines (93 loc) · 2.38 KB
/
api-helper.service.ts
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
94
95
96
97
98
99
100
101
102
103
104
105
106
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
const base_url: string = 'http://localhost:3000';
@Injectable({
providedIn: 'root',
})
export class ApiHelperService {
constructor(private http: HttpClient) { }
public get({
endpoint,
queryParams = {},
}: {
endpoint: string;
queryParams?: any;
}): Promise<any> {environment
return this.request({ endpoint, method: 'GET', queryParams });
}
public post({
endpoint,
data = {},
queryParams = {},
}: {
endpoint: string;
data?: any;
queryParams?: any;
}): Promise<any> {
return this.request({ endpoint, method: 'POST', data, queryParams });
}
public put({
endpoint,
data = {},
queryParams = {},
}: {
endpoint: string;
data?: any;
queryParams?: any;
}): Promise<any> {
return this.request({ endpoint, method: 'PUT', data, queryParams });
}
public delete({
endpoint,
data = {},
queryParams = {},
}: {
endpoint: string;
data?: any;
queryParams?: any;
}): Promise<any> {
return this.request({ endpoint, method: 'DELETE', data, queryParams });
}
public async request({
endpoint,
method = 'GET',
data = {},
queryParams = {},
}: {
endpoint: string;
method?: string;
data?: object;
queryParams?: any;
}): Promise<any> {
const methodWanted = method.toLowerCase();
const url = base_url + endpoint;
const requestOptions = {
params: queryParams,
};
console.log(method, url, JSON.stringify(requestOptions), JSON.stringify(data));
let req: Observable<any>;
if (methodWanted === 'get') {
req = this.http.get(url, { ...requestOptions, observe: 'response' });
} else if (methodWanted === 'post') {
req = this.http.post(url, data, {
...requestOptions,
observe: 'response',
});
} else if (methodWanted === 'put') {
req = this.http.put(url, data, {
...requestOptions,
observe: 'response',
});
} else {
req = this.http.delete(url, { ...requestOptions, observe: 'response' });
}
if (!req) {
throw new Error(`error calling ${url} with method ${methodWanted}`);
}
return await req.toPromise().then((res) => {
return res.body;
});
}
}