-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathserver-connection.js
106 lines (95 loc) · 2.36 KB
/
server-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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
var NanoEvents = require('nanoevents')
/**
* Logux connection for server WebSocket.
*
* @param {WebSocket} ws WebSocket instance
*
* @example
* import { ServerConnection } from 'logux-websocket'
* import { Server } from 'ws'
*
* wss.on('connection', function connection(ws) {
* const connection = new ServerConnection(ws)
* const sync = new ServerSync('server', log, connection, opts)
* })
*
* @class
*/
function ServerConnection (ws) {
/**
* Is connection is enabled.
* @type {boolean}
*/
this.connected = true
this.emitter = new NanoEvents()
this.ws = ws
var self = this
this.ws.on('message', function (msg) {
var data
try {
data = JSON.parse(msg)
} catch (e) {
self.error(msg)
return
}
self.emitter.emit('message', data)
})
this.ws.on('close', function () {
self.connected = false
self.emitter.emit('disconnect')
})
}
ServerConnection.prototype = {
/**
* Part of Connection API, but could not be released for this connection.
*
* @return {undefined}
*/
connect: function connect () {
throw new Error('ServerConnection accepts already connected WebSocket ' +
'instance and could not reconnect it')
},
/**
* Finish current connection.
*
* After disconnection, connection could be started again
* by @{link Connection#connect}.
*
* @return {undefined}
*/
disconnect: function disconnect () {
this.ws.close()
},
/*
* Subscribe for connection events. It should implement nanoevents API.
* Supported events:
*
* * `disconnect`: connection was closed by any side.
* * `message`: message was receive from other node.
* * `error`: message was wrong.
*
* @param {"disconnect"|"message"|"error"} event The event name.
* @param {function} listener The listener function.
*
* @return {function} Unbind listener from event.
*/
on: function on (event, listener) {
return this.emitter.on(event, listener)
},
/**
* Send message to connection.
*
* @param {Message} message Message to be sent
*
* @return {undefined}
*/
send: function send (message) {
this.ws.send(JSON.stringify(message))
},
error: function error (message) {
var err = new Error('Wrong message format')
err.received = message
this.emitter.emit('error', err)
}
}
module.exports = ServerConnection