-
Notifications
You must be signed in to change notification settings - Fork 3
/
ws.js
44 lines (36 loc) · 966 Bytes
/
ws.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
const WebSocket = require('ws')
const _ = require('lodash')
const uuid = require('short-uuid')
const { MESSAGE_TYPES } = require('./constants')
const sessions = {}
function createWSConnection(server) {
const ws = new WebSocket.Server({ server })
ws.on('connection', session => {
sendMessageToSession(session, MESSAGE_TYPES.CONNECTION, { status: 'ok' })
const sessionId = uuid.generate()
sessions[sessionId] = session
session.on('close', () => {
delete sessions[sessionId]
session = null
})
})
}
const sendMessageToSession = (session, type, message) =>
session.send(
JSON.stringify({
type,
message,
})
)
function sendMessage(type, message) {
_.each(sessions, session => {
if (session.readyState !== 3) {
sendMessageToSession(session, type, message)
}
})
}
module.exports = {
createWSConnection: createWSConnection,
MESSAGE_TYPES: MESSAGE_TYPES,
sendMessage: sendMessage,
}