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
|
class DB {
constructor(id) {
this.id = id;
}
async fetchEntries(params) {
return loadFromDatabaseActivity(this.id, params)
}
async saveEntry(json) {
return addEntryToDatabaseActivity(this.id, json);
}
}
async function loadFromDatabaseActivity(id, params) {
let dbUrl = `${window.location.origin}/mod/data/view.php?id=${id}&mode=list&perpage=1000`;
// TODO(muhq): Why does this not include entries?
if (params) {
dbUrl += "&filter=1&advanced=1";
for (const param in params) {
dbUrl += `&${param}=${encodeURIComponent(params[param])}`
}
}
const dbRes = await fetch(encodeURI(dbUrl));
const dbDoc = new DOMParser().parseFromString(await dbRes.text(), 'text/html');
let data = [];
dbDoc.querySelectorAll('.db-row').forEach(row => {
let entry = {};
row.querySelectorAll('.db-cell').forEach(field => {
const key = field.dataset.key;
const value = field.innerText.trim();
entry[key] = value;
});
data.push(entry);
});
return data;
}
async function addEntryToDatabaseActivity(id, json) {
const url = `/mod/data/edit.php?id=${id}`;
const editRes = await fetch(url);
const editDoc = new DOMParser().parseFromString(await editRes.text(), 'text/html');
const form = editDoc.querySelector('div[role="main"] > form');
const formData = new FormData(form);
for (const key in formData.keys()) {
if (k.startsWith("field_")) {
formData.set(key, json);
// We found our json key
break;
}
}
formData.set("saveandview", "Speichern");
return await fetch("/mod/data/edit.php", {
method: "POST",
// Set the FormData instance as the request body
body: formData,
});
}
export { DB, loadFromDatabaseActivity, addEntryToDatabaseActivity };
|