-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathclient.js
75 lines (70 loc) · 1.96 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
'use strict';
const transport = {};
transport.http = (url) => (structure) => {
const api = {};
const services = Object.keys(structure);
for (const name of services) {
api[name] = {};
const service = structure[name];
const methods = Object.keys(service);
for (const method of methods) {
api[name][method] = (...args) =>
new Promise((resolve, reject) => {
fetch(`${url}/api/${name}/${method}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ args }),
}).then((res) => {
if (res.status === 200) resolve(res.json());
else reject(new Error(`Status Code: ${res.status}`));
});
});
}
}
return Promise.resolve(api);
};
transport.ws = (url) => (structure) => {
const socket = new WebSocket(url);
const api = {};
const services = Object.keys(structure);
for (const name of services) {
api[name] = {};
const service = structure[name];
const methods = Object.keys(service);
for (const method of methods) {
api[name][method] = (...args) =>
new Promise((resolve) => {
const packet = { name, method, args };
socket.send(JSON.stringify(packet));
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
resolve(data);
};
});
}
}
return new Promise((resolve) => {
socket.addEventListener('open', () => resolve(api));
});
};
const scaffold = (url) => {
const protocol = url.startsWith('ws:') ? 'ws' : 'http';
return transport[protocol](url);
};
(async () => {
const api = await scaffold('http://localhost:8001')({
auth: {
signin: ['login', 'password'],
signout: [],
restore: ['token'],
},
messenger: {
method: ['arg'],
},
});
const data = await api.auth.signin({
login: 'marcus',
password: 'marcus',
});
console.dir({ data });
})();