-
Notifications
You must be signed in to change notification settings - Fork 4
/
mini_backend.js
111 lines (86 loc) · 2.74 KB
/
mini_backend.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
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
107
108
109
110
111
let jsonFromServer = {};
let BASE_SERVER_URL;
const backend = {
setItem: function(key, item) {
jsonFromServer[key] = item;
return saveJSONToServer();
},
getItem: function(key) {
if (!jsonFromServer[key]) {
return null;
}
return jsonFromServer[key];
},
deleteItem: function(key) {
delete jsonFromServer[key];
return saveJSONToServer();
}
};
window.onload = async function() {
downloadFromServer();
}
async function downloadFromServer() {
let result = await loadJSONFromServer();
jsonFromServer = JSON.parse(result);
console.log('Loaded', result);
}
function setURL(url) {
BASE_SERVER_URL = url;
}
/**
* Loads a JSON or JSON Array to the Server
* payload {JSON | Array} - The payload you want to store
*/
async function loadJSONFromServer() {
let response = await fetch(BASE_SERVER_URL + '/nocors.php?json=database&noache=' + (new Date().getTime()));
return await response.text();
}
function loadJSONFromServerOld() {
return new Promise(function(resolve, reject) {
let xhttp = new XMLHttpRequest();
let proxy = determineProxySettings();
let serverURL = proxy + BASE_SERVER_URL + '/nocors.php?json=database&noache=' + (new Date().getTime());
xhttp.open('GET', serverURL);
xhttp.onreadystatechange = function(oEvent) {
if (xhttp.readyState === 4) {
if (xhttp.status >= 200 && xhttp.status <= 399) {
resolve(xhttp.responseText);
} else {
reject(xhttp.statusText);
}
}
};
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhttp.send();
});
}
/**
* Saves a JSON or JSON Array to the Server
*/
function saveJSONToServer() {
return new Promise(function(resolve, reject) {
let xhttp = new XMLHttpRequest();
let proxy = determineProxySettings();
let serverURL = proxy + BASE_SERVER_URL + '/save_json.php';
xhttp.open('POST', serverURL);
xhttp.onreadystatechange = function(oEvent) {
if (xhttp.readyState === 4) {
if (xhttp.status >= 200 && xhttp.status <= 399) {
resolve(xhttp.responseText);
} else {
reject(xhttp.statusText);
}
}
};
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhttp.send(JSON.stringify(jsonFromServer));
});
}
function determineProxySettings() {
return '';
if (window.location.href.indexOf('.developerakademie.com') > -1) {
return '';
} else {
return 'https://cors-anywhere.herokuapp.com/';
}
}