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
|
async function json(method, url, data, headers, returnJson) {
const options = {
method: method,
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: headers || {
"Content-Type": "application/json"
},
redirect: "follow",
referrerPolicy: "no-referrer",
};
if (data != null) {
options.body = JSON.stringify(data);
}
const result = await fetch(url, options);
if (returnJson) {
if (result.status >= 200 && result.status < 300) {
return result.json();
} else {
return Promise.reject({
response: result,
json: await result.json()
});
}
} else {
return result;
}
}
async function file(url, data, headers) {
const options = {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
body: data,
redirect: "follow",
referrerPolicy: "no-referrer",
};
return await fetch(url, options);
}
const backend = {
get: (url = "", headers = null) => {
return json("GET", url, null, headers);
},
post: (url = "", data = null, headers = null) => {
return json("POST", url, data, headers);
},
put: (url = "", data = null, headers = null) => {
return json("PUT", url, data, headers);
},
delete: (url = "", data = null, headers = null) => {
return json("DELETE", url, data, headers);
},
getJson: (url = "", headers = null) => {
return json("GET", url, null, headers, true);
},
postJson: (url = "", data = null, headers = null) => {
return json("POST", url, data, headers, true);
},
putJson: (url = "", data = null, headers = null) => {
return json("PUT", url, data, headers, true);
},
deleteJson: (url = "", data = null, headers = null) => {
return json("DELETE", url, data, headers, true);
},
postFile: (url = "", data = null, headers = null) => {
return file(url, data, headers);
},
};
export default backend;
|