-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
92 lines (84 loc) · 3.42 KB
/
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
86
87
88
89
90
91
92
"use strict";
const fetch = (() => {
if (typeof window !== "undefined") {
// Browser runtime
return window.fetch;
} else if (typeof process !== "undefined") {
// Node.js runtime
return require("node-fetch");
} else {
throw new Error("Unknown JavaScript runtime!");
}
})();
class uDBClient {
constructor(url) {
const jsendRequest = (url, method, body) =>
new Promise((resolve, reject) => {
if (method === "GET" || method === "HEAD") body = null;
else body = body != null ? JSON.stringify(body) : "";
fetch(url, {
method: method,
body: body,
redirect: "follow",
}).then(async (httpResponse) => {
try {
if (httpResponse.status == 200) {
const response = await httpResponse.json();
if (response.status === "success")
resolve(response.data);
else if (response.status === "error")
throw Error(response.message);
else throw Error(JSON.stringify(response.data));
} else throw Error(`Got HTTP ${httpResponse.status}`);
} catch (err) {
reject(err);
}
}, reject);
});
const sendApiGetRequest = (store, id, doc) =>
new Promise((resolve, reject) => {
let requestUrl = url;
if (store != null) requestUrl += `&store=${store}`;
if (id != null) requestUrl += `&id=${id}`;
return jsendRequest(requestUrl, "GET", doc).then(
resolve,
reject
);
});
const sendApiPostRequest = (store, id, doc) =>
new Promise((resolve, reject) => {
let requestUrl = url;
if (store != null) requestUrl += `&store=${store}`;
if (id != null) requestUrl += `&id=${id}`;
return jsendRequest(requestUrl, "POST", doc).then(
resolve,
reject
);
});
// Public functions
this.getStores = () => sendApiGetRequest(null, null, null);
this.store = (store) => {
this.getAll = () => sendApiGetRequest(store, null, null);
this.get = async (id) => {
if (typeof id !== "string")
throw new Error('id must be of type "string"');
return await sendApiGetRequest(store, id, null);
};
this.put = async (doc) => {
if (doc == null || typeof doc !== "object")
throw new Error(
'doc must be of type "object" and not "null"'
);
return await sendApiPostRequest(store, null, doc);
};
this.delete = async (id) => {
if (typeof id !== "string")
throw new Error('id must be of type "string"');
return await sendApiPostRequest(store, id, null);
};
this.clear = () => sendApiPostRequest(store, null);
return this;
};
}
}
if (typeof process !== "undefined") module.exports = uDBClient;