-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrestService.js
68 lines (64 loc) · 2.2 KB
/
restService.js
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
//import { resolve } from "core-js/fn/promise";
import conf from "../config.js"
function getUrl(url) {
return `${conf.apiUrl}${url.startsWith("/") ? "" : "/"}${url}`;
}
function getHeader(token) {
const header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
if (token !== undefined) {
header['Authorization'] = `Bearer ${token}`;
}
return header;
}
class RestService {
login(username, password) {
return new Promise((resolve, reject) => {
this.postJson("api/user/login", { username: username, password: password })
.then(data => {
this.username = data.cn;
this.token = data.token;
this.role = data.role;
resolve(data);
})
.catch(err => reject(err));
});
}
get isAuthenticated() {
return this.token !== undefined;
}
getJson(url) {
return this.sendRequest(url, 'GET');
}
postJson(url, data) {
return this.sendRequest(url, 'POST', data);
}
sendRequest(url, method, data) {
return new Promise((resolve, reject) => {
const fetchParams = {
method: method,
headers: getHeader(this.token)
}
if (method != 'GET' && data !== undefined) { fetchParams.body = JSON.stringify(data); }
fetch(getUrl(url), fetchParams)
.then(response => {
if (response.ok) {
response.json()
.then(data => resolve(data))
.catch(() => resolve({})); // HTTP 201 no content
return;
}
if (response.status == 400) {
response.json()
.then(data => { reject({ status: response.status, data: data }); })
return;
}
reject({ status: response.status });
})
.catch(() => reject({ status: 0 })); // Server nicht erreichbar
});
}
}
export default new RestService();