forked from cerebral/overmind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackendConnector.ts
More file actions
92 lines (84 loc) · 2.18 KB
/
BackendConnector.ts
File metadata and controls
92 lines (84 loc) · 2.18 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { ipcRenderer } from 'electron'
type Message = {
type: string
port: string
}
type MessageCallback = (error: Error, message?: Message) => void
class Port {
port: string
messageCallback: MessageCallback
connector: BackendConnector
connectionResolver: Function
connectionRejecter: Function
constructor(
connector: BackendConnector,
port: string,
messageCallback: MessageCallback
) {
this.port = port
this.messageCallback = messageCallback
this.connector = connector
ipcRenderer.on('port:added', this.onPortAdded)
ipcRenderer.on('port:exists', this.onPortExists)
}
connect() {
return new Promise((resolve, reject) => {
this.connectionResolver = resolve
this.connectionRejecter = reject
ipcRenderer.send('port:add', this.port)
})
}
equals(port: string) {
return this.port === port
}
onPortAdded = (_, addedPort) => {
if (addedPort === this.port) {
ipcRenderer.on('message', this.onMessage)
this.connector.sendMessage(this.port, 'ping')
}
}
onPortExists = (_, port) => {
if (port === this.port) {
this.connectionRejecter(
new Error('Something running on this port already')
)
}
}
onMessage = (_, message) => {
if (message.port !== this.port) {
return
}
if (message.type === 'ping') {
this.connector.sendMessage(this.port, 'pong')
return this.connectionResolver()
}
this.messageCallback(message)
}
}
class BackendConnector {
addedPorts: Port[] = []
sendMessage(port: string, eventName: string, payload: object = null) {
ipcRenderer.send('message', {
port,
type: eventName,
data: payload,
})
}
addPort(port: string, messageCallback: MessageCallback) {
if (
this.addedPorts.filter((portInstance) => portInstance.equals(port)).length
) {
throw new Error('This port already exists')
}
const portInstance = new Port(this, port, messageCallback)
portInstance.connect()
this.addedPorts.push(portInstance)
}
removePort(port: string) {
ipcRenderer.send('port:remove', port)
}
relaunch() {
ipcRenderer.send('relaunch')
}
}
export default BackendConnector