-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommander.js
66 lines (55 loc) · 1.43 KB
/
commander.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 debug = require('debug')('twlv-chat-api:commander');
class Commander {
constructor ({ node }) {
this.node = node;
this.peers = [];
this._onMessage = this._onMessage.bind(this);
}
putPeer (address, profile) {
let lastSeen = new Date();
this.peers.push({ address, profile, lastSeen });
}
start () {
this.node.on('message', this._onMessage);
}
stop () {
this.node.removeListener('message', this._onMessage);
}
async sendReply (to, command, data) {
try {
await this.node.send({
to,
command: `twlv-chat-api:${command}`,
payload: JSON.stringify(data),
});
} catch (err) {
console.error('sendreply err', err);
}
}
async _onMessage (message) {
if (!message.command.startsWith('twlv-chat-api:')) {
return;
}
let from = message.from;
let command = message.command.split('twlv-chat-api:').pop();
let data = JSON.parse(message.payload);
debug('cmd', command);
let fn;
try {
fn = require(`./commands/${command}`);
} catch (err) {
debug('Invalid command handler "%s"', command);
}
if (fn) {
try {
let reply = await fn({ ctx: this, from, data });
if (typeof reply !== 'undefined') {
await this.sendReply(from, command, reply);
}
} catch (err) {
console.error('Message handler err', err);
}
}
}
}
module.exports = { Commander };