This repository has been archived by the owner on Jul 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
replitdb-client.js
85 lines (67 loc) · 1.5 KB
/
replitdb-client.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
const fetch = require("node-fetch");
class Client {
constructor(key) {
if (key) {
this.key = key;
} else {
this.key = process.env.REPLIT_DB_URL;
}
}
async get(key) {
const val = await fetch(`${this.key}/${encodeURIComponent(key)}`);
return val.text();
}
async set(keyT, value) {
const key = encodeURIComponent(keyT);
const strValue = encodeURIComponent(value);
await fetch(this.key, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: key + "=" + strValue,
});
}
async delete(key) {
await fetch(this.key + "/" + encodeURIComponent(key), { method: "DELETE" });
}
async list(prefix = "") {
return await fetch(
`${this.key}?encode=true&prefix=${encodeURIComponent(prefix)}`
).then((r) => r.text()).then((t) => {
if (t.length === 0) {
return [];
}
return t.split("\n").map(decodeURIComponent);
});
}
async empty() {
const promises = [];
for (const key of await this.list()) {
promises.push(this.delete(key));
}
await Promise.all(promises);
}
async getAll() {
let output = {};
for (const key of await this.list()) {
let value = await this.get(key);
output[key] = value;
}
return output;
}
async setAll(obj) {
for (const key in obj) {
await this.set(key, obj[key]);
}
}
async deleteMultiple(...args) {
const promises = [];
for (const arg of args) {
promises.push(this.delete(arg));
}
await Promise.all(promises);
return this;
}
}
module.exports = new Client();