-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathclient.js
86 lines (76 loc) · 1.95 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
'use strict';
const API_URL = 'ws://localhost:8001';
const getTransport = (url) => {
let socket;
const protocol = url.split(':')[0];
const transports = {
ws: (name, method) => {
if (!socket) socket = new WebSocket(url);
return (...args) => {
return new Promise((resolve) => {
const packet = { name, method, args };
socket.send(JSON.stringify(packet));
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
resolve(data);
};
});
};
},
http:
(name, method, methodArgs) =>
(...args) => {
const urlParts = [url, name, method];
if (methodArgs[0] === 'id') urlParts.push(args.shift());
return fetch(urlParts.join('/'), {
method: 'POST',
body: JSON.stringify(args),
}).then((response) => response.json());
},
};
return transports[protocol];
};
const scaffold = (url, structure) => {
const transport = getTransport(url);
const api = {};
const services = Object.keys(structure);
for (const serviceName of services) {
api[serviceName] = {};
const service = structure[serviceName];
const methods = Object.keys(service);
for (const methodName of methods) {
api[serviceName][methodName] = transport(
serviceName,
methodName,
service[methodName],
);
}
}
return api;
};
const api = scaffold(API_URL, {
user: {
create: ['record'],
read: ['id'],
update: ['id', 'record'],
delete: ['id'],
find: ['mask'],
},
city: {
read: ['id'],
create: ['record'],
update: ['id', 'record'],
delete: ['id'],
},
country: {
read: ['id'],
create: ['record'],
update: ['id', 'record'],
delete: ['id'],
},
});
// socket.addEventListener('open', async () => {
// const data = await api.user.read(3);
// console.dir({ data });
// });
(async () => console.log(await api.user.read(3)))();