-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (49 loc) · 1.26 KB
/
index.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
var WebSocket = require('isomorphic-ws')
module.exports = function(url, opt) {
if (!opt) opt = {}
if (typeof opt.timeout == 'undefined') opt.timeout = 1
var socket, events = {}
var EVENTS = ['message', 'open', 'close', 'error']
for (var i = 0; i < EVENTS.length; i++) {
events[EVENTS[i]] = []
}
function on(name, fn) {
events[name].push(fn)
}
function run(name, ...args) {
for (var i = 0; i < events[name].length; i++) {
events[name][i](...args)
}
}
function open(resolve, reject) {
socket = new WebSocket(url)
socket.onmessage = function(event) {
var data = JSON.parse(event.data)
run('message', data, event)
}
socket.onopen = function(event) {
if (resolve) resolve(api)
run('open', api, event)
}
socket.onerror = function(event) {
if (reject) reject(event)
run('error', event)
}
socket.onclose = function(event) {
if (opt.timeout) {
setTimeout(open, opt.timeout)
}
run('close', event)
}
}
function close(code) {
socket.close(code || 1000)
}
function send(params) {
if (socket.readyState == 1) {
socket.send(JSON.stringify(params))
}
}
var api = { on, open, send, close }
return new Promise(open)
}