-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBismuthNative.ts
More file actions
77 lines (63 loc) · 2.64 KB
/
BismuthNative.ts
File metadata and controls
77 lines (63 loc) · 2.64 KB
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
import io from 'socket.io-client';
import * as net from 'net';
import { isBoolean } from 'util';
const version = '1.0.0';
export interface BismuthNativeConstructorParam {
server: string //'127.0.0.1'
port: number // 5658,
verbose: boolean // false
}
export class BismuthNative {
private server: string;
private port: number;
private verbose: boolean;
protected socket: net.Socket;
public constructor({ server = '127.0.0.1', port = 5658, verbose = false }: BismuthNativeConstructorParam) {
this.server = server, this.port = port, this.verbose = verbose;
if (verbose)
console.log(Date.now(), 'Connecting to node with', { server, port, verbose });
// Generate promise that resolves when connection est.
this.socket = new Promise((resolve, reject) => {
let socket = net.createConnection({ host: server, port, writable: true, readable: true }, () => {
if(verbose)
console.log('Connected to node !');
return resolve(socket);
})
})
}
public async getConnection(): Promise<net.Socket> {
if (this.verbose)
console.log('Get connection is waiting on socket..');
return await this.socket;
}
private _prepareRpcPayload(data) {
// Only json encode stuff that is not a number or boolean to have correct headers
let dataToSend = (!isNaN(data) || isBoolean(data)) ? data.toString() : JSON.stringify(data);
return `${dataToSend.length.toString().padStart(10, '0')}${dataToSend}`
}
public async command(command: string, options?: any[]): Promise<any> {
let socket = await this.getConnection();
return new Promise((resolve, reject) => {
let payload = this._prepareRpcPayload(command);
if (this.verbose)
console.log('Sending Payload', payload);
socket.write(payload);
if(options && options.length)
options.forEach(option=> {
let optionPayload = this._prepareRpcPayload(option);
if (this.verbose)
console.log('Sending Option', optionPayload);
socket.write(optionPayload)
});
socket.on('data', (response) => {
if (this.verbose)
console.log('Recieved data from host', response.toString('utf8'));
try {
return resolve(JSON.parse(response.toString('utf8').substr(10)));
} catch(err){
reject(err)
}
});
})
}
}