-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdatabase.js
102 lines (84 loc) · 2.52 KB
/
database.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
/// https://firebase.google.com/docs/database/rest/start
export class Database {
static #url = 'https://en-passant-405713-default-rtdb.firebaseio.com/';
static #SECRET = Deno.env.get('FIREBASE_SECRET');
static async get(key) {
for(let tries = 0; tries < 3; tries++){
try
{
return await fetch(this.#url + encodeURIComponent(key) + '/.json?auth=' + this.#SECRET)
.then(e => e.text())
.then(value => {
if (!value) return null;
try { value = JSON.parse(value); }
catch { return null; }
if (value === undefined || value === null || value.error !== undefined) return null;
return value;
});
}
catch (e)
{
console.log("error with GET, retry number " + tries);
}
}
}
static async set(key, value) {
for(let tries = 0; tries < 3; tries++){
try {
await fetch(this.#url + encodeURIComponent(key) + '/.json?auth=' + this.#SECRET, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(value),
});
break
}
catch (e)
{
console.log("error with SET, retry number " + tries);
}
}
}
static async push(key, value) {
key = encodeURIComponent(key);
const shallow = await fetch(this.#url + key + '/.json?shallow=true&auth=' + this.#SECRET)
.then(e => e.text())
.then(value => {
if (!value) return null;
try { value = JSON.parse(value); }
catch { return null; }
if (value === undefined || value === null || value.error !== undefined) return null;
return value;
});
if (shallow === null || shallow === undefined || Object.keys(shallow) === 0) {
await fetch(this.#url + key + '/.json?auth=' + this.#SECRET, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([value]),
});
return;
}
const length = Object.keys(shallow).length;
await fetch(this.#url + key + '/' + length + '/.json?auth=' + this.#SECRET, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(value),
});
}
static async delete(key) {
await fetch(
this.#url + encodeURIComponent(key) + '/.json?auth=' + this.#SECRET,
{ method: "DELETE" }
);
}
static async dictionary() {
return await fetch(this.#url + '/.json?auth=' + this.#SECRET)
.then(e => e.text())
.then(value => {
if (!value) return null;
try { value = JSON.parse(value); }
catch { return null; }
if (value === undefined || value === null || value.error !== undefined) return null;
return value;
});
}
}