-
Notifications
You must be signed in to change notification settings - Fork 70
/
client-ipc.js
93 lines (79 loc) · 2.09 KB
/
client-ipc.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
88
89
90
91
92
93
// Init
async function init() {
const socketName = await window.getServerSocket()
connectSocket(socketName, () => {
console.log('Connected!')
})
}
init()
// State
const replyHandlers = new Map()
const listeners = new Map()
let messageQueue = []
let socketClient = null
// Functions
function connectSocket(name, onOpen) {
window.ipcConnect(name, function(client) {
client.on('message', data => {
const msg = JSON.parse(data)
if (msg.type === 'error') {
// Up to you whether or not to care about the error
const { id } = msg
replyHandlers.delete(id)
} else if (msg.type === 'reply') {
const { id, result } = msg
const handler = replyHandlers.get(id)
if (handler) {
replyHandlers.delete(id)
handler.resolve(result)
}
} else if (msg.type === 'push') {
const { name, args } = msg
const listens = listeners.get(name)
if (listens) {
listens.forEach(listener => {
listener(args)
})
}
} else {
throw new Error('Unknown message type: ' + JSON.stringify(msg))
}
})
client.on('connect', () => {
socketClient = client
// Send any messages that were queued while closed
if (messageQueue.length > 0) {
messageQueue.forEach(msg => client.emit('message', msg))
messageQueue = []
}
onOpen()
})
client.on('disconnect', () => {
socketClient = null
})
})
}
function send(name, args) {
return new Promise((resolve, reject) => {
let id = window.uuid.v4()
replyHandlers.set(id, { resolve, reject })
if (socketClient) {
socketClient.emit('message', JSON.stringify({ id, name, args }))
} else {
messageQueue.push(JSON.stringify({ id, name, args }))
}
})
}
function listen(name, cb) {
if (!listeners.get(name)) {
listeners.set(name, [])
}
listeners.get(name).push(cb)
return () => {
let arr = listeners.get(name)
listeners.set(name, arr.filter(cb_ => cb_ !== cb))
}
}
function unlisten(name) {
listeners.set(name, [])
}