UNPKG

2.16 kBJavaScriptView Raw
1var WebSocketServer = require('ws').Server
2var debug = require('debug')('ldnode:ws')
3var InMemory = require('./in-memory')
4var parallel = require('run-parallel')
5var url = require('url')
6
7module.exports = WsServer
8
9function defaultToChannel(iri) {
10 return url.parse(iri).path
11}
12
13function WsServer (server, opts) {
14 var self = this
15
16 opts = opts || {}
17 this.suffix = opts.suffix || '.changes'
18 this.store = opts.store || new InMemory(opts)
19 var toChannel = opts.toChannel || defaultToChannel
20
21 // Starting WSS server
22 var wss = new WebSocketServer({
23 server: server,
24 clientTracking: false,
25 path: opts.path
26 })
27
28 // Handling a single connection
29 wss.on('connection', function (client) {
30 debug('New connection')
31 // var location = url.parse(client.upgradeReq.url, true)
32
33 // Handling messages
34 client.on('message', function (message) {
35 debug('New message: ' + message)
36
37 if (!message || typeof message !== 'string') {
38 return
39 }
40
41 var tuple = message.split(' ')
42 var command = tuple[0]
43 var iri = tuple[1]
44
45 // Only accept 'sub http://example.tld/hello'
46 if (tuple.length < 2 || command !== 'sub') {
47 return
48 }
49
50 var channel = toChannel ? toChannel(iri) : iri
51 self.store.subscribe(channel, iri, client, function (err, uuid) {
52 if (err) {
53 // TODO Should return an error
54 return
55 }
56
57 client.send('ack ' + tuple[1])
58 })
59 })
60
61 // Respond to ping
62 client.on('ping', function () {
63 client.pong()
64 })
65 })
66}
67
68WsServer.prototype.publish = function (iri, callback) {
69 this.store.get(iri, function (err, subscribers) {
70
71 if (err) {
72 if (callback) return callback(err)
73 else return
74 }
75
76 if (!subscribers) {
77 subscribers = {}
78 }
79
80 var tasks = Object.keys(subscribers)
81 .map(function (uuid) {
82 return function (cb) {
83 var client = subscribers[uuid][0]
84 var channel = subscribers[uuid][1]
85 debug('pub ' + channel + ' to ' + client.uuid)
86 client.send('pub ' + channel)
87 }
88 })
89
90 parallel(tasks, callback)
91 })
92}