-
Notifications
You must be signed in to change notification settings - Fork 0
/
connect.js
87 lines (83 loc) · 2.36 KB
/
connect.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
87
const configLoader = require('./components/configLoader.js')
const config = configLoader(require('./config/connect.js'))
const net = require('net')
class connect {
constructor(connectionLink) {
this.link = config.$[connectionLink]
this.config = config
this.lag = []
this.makeNewConnection()
this.interval = null
this.alreadyGotError = -1
}
makeNewConnection() {
this.conn = net.connect(this.link)
this.weGotNewConnection()
}
onMessage(fn) {
this._onMessage = fn
}
weGotNewConnection() {
this.conn.on('data', (data)=>{
data = JSON.parse(data)
if(data.context=="connectionEstablished") {
this.override()
this.execute()
}
else this._onMessage(data)
})
this.conn.on('connect', ()=>{
clearInterval(this.interval)
this.interval = null
this.alreadyGotError = -1
})
this.conn.on('end', ()=>{
this.reverseOverride()
})
this.conn.on('error', (error)=>{
if(error.code=='ENOENT') {
this.alreadyGotError++
if(this.alreadyGotError>0) {
if(this.alreadyGotError%60===0) console.info(`[ ! ] ENOENT error persists for ${this.alreadyGotError/60} minutes... (${this.link})`)
return
}
}
console.info(`[ ! ] Connector error (${this.link}) :`, error)
})
this.conn.on('close', ()=>{
this.reverseOverride()
if(this.interval==null) this.notConnected()
})
}
notConnected() {
this.interval = setInterval(()=>{
this.makeNewConnection()
}, 1000)
}
reverseOverride() {
this.send = (msg)=>{
this.lag.push(JSON.stringify(msg))
}
}
override() {
this.send = (msg)=>{
this.conn.write(JSON.stringify(msg))
}
}
execute() {
this.lag.forEach((x)=>{
this.conn.write(x)
})
this.lag = []
}
send(msg) {
this.lag.push(JSON.stringify(msg))
}
on(event, fn) {
this.conn.on(event, fn)
}
}
const makeConn = (link)=>{
return new connect(link)
}
module.exports = { makeConnection: makeConn }