This repository has been archived by the owner on Nov 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executor.js
66 lines (64 loc) · 1.71 KB
/
executor.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
const { randomId } = require("./common");
class Executor {
constructor(transport) {
this.transport = transport;
this.isConnected = false;
this.connect();
this.promises = new Map();
}
connect() {
this.transport.on("message", data => this.handleData(data));
this.transport.on("connect", () => this.onConnect());
this.transport.connect();
}
onConnect() {
this.isConnected = true;
}
handleData(data) {
const { id, details, instruction } = data;
if (instruction == "result") {
const { result } = details;
return this.promises.get(id).resolve(result);
} else if (instruction == "paths") {
const { paths } = details;
return this.promises.get(id).resolve(paths);
}
}
call(path, args) {
const id = randomId(32);
const promise = new Promise(resolve => {
this.promises.set(id, { resolve });
});
const send = () =>
this.transport.send({
instruction: "call",
details: { path, args },
id,
});
if (this.isConnected) send();
else this.transport.on("connect", send);
return promise;
}
getFunction(path) {
return (...args) => this.call(path, args);
}
async getFunctions(path) {
const id = randomId(32);
const promise = new Promise(resolve => {
this.promises.set(id, { resolve });
});
const send = () =>
this.transport.send({
instruction: "getPaths",
details: { path },
id,
});
if (this.isConnected) send();
else this.transport.on("connect", send);
const paths = await promise;
const fns = {};
for (const path of paths) fns[path] = this.getFunction(path);
return fns;
}
}
module.exports.Executor = Executor;