forked from gbezyuk/logux-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
browser-connection.js
85 lines (71 loc) · 1.77 KB
/
browser-connection.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
var NanoEvents = require('nanoevents')
/**
* Logux connection for browser WebSocket.
*
* @param {string} url WebSocket server URL.
*
* @example
* import { BrowserConnection } from 'logux-websocket'
*
* const connection = new BrowserConnection('wss://logux.example.com/')
* const sync = new ClientSync(nodeId, log, connection, opts)
*
* @class
* @extends Connection
*/
function BrowserConnection (url) {
this.connected = false
this.emitter = new NanoEvents()
this.url = url
}
BrowserConnection.prototype = {
connect: function connect () {
if (!window.WebSocket) {
throw new Error('Browser has no WebSocket support')
}
this.emitter.emit('connecting')
this.ws = new window.WebSocket(this.url)
var self = this
this.ws.onopen = function () {
self.connected = true
self.emitter.emit('connect')
}
this.ws.onclose = function () {
self.connected = false
self.emitter.emit('disconnect')
}
this.ws.onmessage = function (event) {
var data
try {
data = JSON.parse(event.data)
} catch (e) {
self.error(event.data)
return
}
self.emitter.emit('message', data)
}
},
disconnect: function disconnect () {
if (this.ws) {
this.ws.close()
this.ws.onclose()
this.ws = undefined
}
},
on: function on (event, listener) {
return this.emitter.on(event, listener)
},
send: function send (message) {
if (this.ws) {
this.ws.send(JSON.stringify(message))
} else {
throw new Error('Start a connection before send a message')
}
},
error: function error (message) {
var err = new Error('Wrong message format')
err.received = message
this.emitter.emit('error', err)
}
}
module.exports = BrowserConnection