UNPKG

1.01 kBJavaScriptView Raw
1/* istanbul ignore file */
2const WebSocket = require('ws')
3const Hookable = require('hookable')
4
5class WS extends Hookable {
6 constructor (options) {
7 super()
8 this.wss = new WebSocket.Server({ noServer: true })
9 this.hook('upgrade', (request, socket, head) => {
10 if (request.url === `/${options.apiPrefix}/ws`) {
11 this.handleUpgrade(request, socket, head)
12 }
13 })
14 }
15
16 serve (req) {
17 this.handleUpgrade(req, req.socket, undefined)
18 }
19
20 handleUpgrade (request, socket, head = '') {
21 return this.wss.handleUpgrade(request, socket, head, (client) => {
22 this.wss.emit('connection', client, request)
23 })
24 }
25
26 /**
27 * Publish event and data to all connected clients
28 * @param {object} data
29 */
30 broadcast (data) {
31 data = JSON.stringify(data)
32
33 for (const client of this.wss.clients) {
34 try {
35 client.send(data)
36 } catch (err) {
37 // Ignore error (if client not ready to receive event)
38 }
39 }
40 }
41}
42
43module.exports = WS