-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
106 lines (104 loc) · 2.47 KB
/
index.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
const axios = require("axios");
const url = `https://github-db.glitch.me/db/api`;
function Client({ db, token }) {
const options = { db, token };
let auth_token;
async function auth() {
try {
if (!auth_token) {
const {data} = await axios.post(`${url}/token`, options);
auth_token = data.token;
axios.defaults.headers.common['Authorization'] = `Bearer ${auth_token}`;
}
} catch (error) {
hanlderError(error);
}
}
async function add({document,identifier}, payload) {
try {
await auth();
const resp = await axios.post(`${url}/add`, {
db: options.db,identifier,
token,
document,
payload
});
return resp.data;
} catch (error) {
hanlderError(error);
}
}
async function update({document,identifier} , payload) {
try {
await auth();
const resp = await axios.post(`${url}/update`, {
db: options.db,
token,
document,
identifier,
payload
});
return resp.data;
} catch (error) {
hanlderError(error);
}
}
async function _delete({document,identifier}) {
try {
await auth();
const resp = await axios.post(`${url}/delete`, {
db: options.db,
token,
document,
identifier
});
return resp.data;
} catch (error) {
hanlderError(error);
}
}
async function fetchOne({document,identifier} ) {
try {
await auth();
const resp = await axios.post(`${url}/fetchOne`, { db: options.db, token, document, identifier });
return resp.data;
} catch (error) {
hanlderError(error);
}
}
async function fetchAll({document,identifier}) {
try {
await auth();
const resp = await axios.post(`${url}/fetchAll`, { db: options.db, token,identifier, document });
return resp.data;
} catch (error) {
hanlderError(error);
}
}
return {
add,
fetchOne,
fetchAll,
delete: _delete,
update
};
}
function hanlderError(error) {
if (error.response) {
throw new Error(error.response.data.message);
} else if (error.request) {
throw error.request;
} else {
throw new Error(error.message);
}
}
async function createDatabase(name,token) {
try {
const resp = await axios.post(`${url}/create-database`, { name,token});
return resp.data;
} catch (error) {
hanlderError(error);
}
}
Client.createDatabase=createDatabase;
module.exports = Client;