-
Notifications
You must be signed in to change notification settings - Fork 0
/
crud.js
87 lines (62 loc) · 2.29 KB
/
crud.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
import { methodsEnum as methods } from "./api.js";
import page from "./node_modules/page/page.mjs"
async function requestHandler(form, body, method, id) {
const path = body.military;
const mentioned_emperor = body['emperor_mentioned'];
if (method == 'POST') {
try {
const response = await methods[method](path, body);
const firebase_id = await response.json();
attach_firebase_id(firebase_id.name, path);
const db_emperor_ref = await emperorRelationship(`${path}/${firebase_id.name}`, mentioned_emperor);
Object.defineProperty(body, 'db_emperor_ref', {value: db_emperor_ref.name, enumerable: true, writable: true, configurable: true});
await methods.PATCH(`${path}/${firebase_id.name}`, body);
}
catch (err) {
alert(err);
throw err;
}
finally {
form.reset();
}
}
else if (method == 'PATCH') {
try {
await methods[method](`${path}/${id}`, body);
alert('Записът е обновен!');
}
catch (err) {
alert(err);
}
finally {
page.redirect(`/${path}/${id}`);
// history.replaceState(history.state, "", `/Monuments/${id}`);
// page.start() - old implementation
}
}
}
async function emperorRelationship(path, mentioned_emperor) {
if(mentioned_emperor == null) return;
if(mentioned_emperor == 'Not applicable') return;
const body = {link: path};
const response = await methods.POST(`/Emperors/${mentioned_emperor}`, body);
return await response.json();
}
async function attach_firebase_id(firebase_id, path, attempts = 0) {
const limit = 5;
if (attempts == limit) {
await methods.DELETE(`${path}/${firebase_id}`);
return alert(`Unable to update firebase id after ${limit} attempts!`);
}
try {
let body = { 'firebase_id': firebase_id };
await methods.PATCH(`${path}/${firebase_id}`, body);
alert(`Записът е добавен в базата данни! Firebase ID: ${firebase_id}`);
}
catch (err) {
attempts++;
attach_firebase_id(firebase_id, attempts);
throw err;
}
}
export { requestHandler }