-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathrestClient.js
41 lines (39 loc) · 1.49 KB
/
restClient.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
export { client }
/**
* Makes a http call to the given url using the given method as http method and data as request body.
*
* @type {RestClient}
* @see RestClient
* @return RestResponse
*/
const client = (url, method = 'GET', data = null) => {
const request = {
method: method, // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json', // 'application/x-www-form-urlencoded'
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
};
if (null != data) {
request.body = JSON.stringify(data)
}
return fetch(url, request)
.then(resp => { // fetch API cares for the general error handling
if (Number(resp.status) === 204) {
console.log("got special", 204); // special: Grails returns this on successful DELETE
return Promise.resolve("ok");
}
if (resp.ok) {
return resp.json()
}
if (Number(resp.status) < 400) {
console.log("status", resp.status);
return resp.text();
}
return Promise.reject(resp.status);
})
};