-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.io-with-get.js
64 lines (50 loc) · 1.1 KB
/
socket.io-with-get.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
const EventEmitter = require('events')
class Socket extends EventEmitter {
constructor(socket, idLength = 3) {
super()
this.ids = []
this.write = socket.write || socket.emit
const callEvent = ([id, value]) => {
if (id in this.ids) {
this.ids[id](value)
delete this.ids[id]
}
}
socket.on(1, callEvent)
socket.on(2, callEvent)
socket.on(0, ([id, event, args]) =>
this.emit(
event,
args,
(data) => this.write(1, [id, data]),
(err) => this.write(2, [id, err])
)
)
this.socket = socket
const pow = Math.pow(10, idLength)
this.newID = () => {
const id = Math.floor(Math.random() * pow)
if (id in this.ids) {
return this.newID()
}
return id
}
}
get(event, data) {
return new Promise(async (resolve, reject) => {
const id = this.newID()
this.ids[id] = resolve
this.write(0, [id, event, data])
})
}
}
module.exports = (socket) => {
const soc = new Socket(socket)
return {
on: (event, cb) =>
soc.on(event, (data, resolve, reject) =>
cb(data).then(resolve, reject)
),
get: (...args) => soc.get(...args),
}
}