-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.js
63 lines (53 loc) · 1.34 KB
/
command.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
const defaultEncoding = require('./encoding')
const { unpack } = require('./unpack')
const messages = require('./messages')
const { pack } = require('./pack')
const crypto = require('crypto')
const varint = require('varint')
class Command {
static id() {
return crypto.randomBytes(32)
}
static get WIRE_TYPE() {
return 0x01
}
static from(buffer, encoding) {
const type = varint.decode(buffer)
if (Command.WIRE_TYPE !== type) {
throw new TypeError('Invalid wire type for Command')
}
encoding = encoding || defaultEncoding
const decoded = messages.Command.decode(unpack(buffer))
const name = decoded.name
const args = decoded.arguments
const cmd = new Command(encoding, name, args.map(decode))
cmd.id = decoded.id
return cmd
function decode(arg) {
return encoding.decode(arg)
}
}
constructor(encoding, name, args, callback) {
this.id = Command.id()
this.name = name
this.encoding = encoding
this.callback = callback
this.arguments = args
}
toJSON() {
return {
id: this.id,
name: this.name,
arguments: this.arguments.map((arg) => this.encoding.encode(arg))
}
}
toBuffer() {
return messages.Command.encode(this.toJSON())
}
pack() {
return pack(Command.WIRE_TYPE, this.toBuffer())
}
}
module.exports = {
Command
}