-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathindex.js
More file actions
80 lines (65 loc) · 2.09 KB
/
index.js
File metadata and controls
80 lines (65 loc) · 2.09 KB
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
class Client {
constructor(apiKey, nameSpace, server) {
this.apiKey = apiKey;
this.nameSpace = nameSpace || 'data';
this.server = server || 'api-bdc.net';
return new Proxy(this, {
get: (target, prop) => {
if (typeof target[prop] !== 'undefined') return target[prop];
return (params) => {
let key = prop;
let method = 'GET';
key = key.replace(/([A-Z])/g, (m) => '-' + m.toLowerCase());
key = key.replace(/^-/, '');
const parts = key.split('-');
if (parts.length > 1) {
const methodTest = parts[0].toUpperCase();
if (['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH', 'HEAD'].includes(methodTest)) {
method = methodTest;
parts.shift();
}
}
const endpoint = parts.join('-');
return this.communicate(endpoint, method, params);
};
}
});
}
communicate(endpoint, method, payload) {
const qs = [];
let data = false;
let hasKey = false;
method = (method || 'GET').toUpperCase();
let url = 'https://' + this.server + '/' + this.nameSpace + '/' + endpoint;
if (payload) {
for (const key in payload) {
if (key === 'key') hasKey = true;
qs.push(encodeURIComponent(key) + '=' + encodeURIComponent(payload[key]));
}
}
if (!hasKey) qs.push('key=' + this.apiKey);
if (qs.length && (method === 'GET' || method === 'HEAD' || method === 'DELETE')) {
url += (url.indexOf('?') === -1 ? '?' : '&') + qs.join('&');
} else if (qs.length) {
data = qs.join('&');
}
return this.talk(method, url, data);
}
async talk(method, url, data) {
const options = { method };
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
options.headers = { 'content-type': 'application/x-www-form-urlencoded' };
}
if (data) options.body = data;
const res = await fetch(url, options);
const json = await res.json();
if (!res.ok) {
throw { error: json, code: res.status };
}
return json;
}
}
// Support both CJS and ESM
module.exports = (apiKey, nameSpace, server) => new Client(apiKey, nameSpace, server);
module.exports.Client = Client;
module.exports.default = module.exports;