1 | var WebSocketServer = require('ws').Server
|
2 | var debug = require('debug')('ldnode:ws')
|
3 | var InMemory = require('./in-memory')
|
4 | var parallel = require('run-parallel')
|
5 | var url = require('url')
|
6 |
|
7 | module.exports = WsServer
|
8 |
|
9 | function defaultToChannel(iri) {
|
10 | return url.parse(iri).path
|
11 | }
|
12 |
|
13 | function 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 |
|
22 | var wss = new WebSocketServer({
|
23 | server: server,
|
24 | clientTracking: false,
|
25 | path: opts.path
|
26 | })
|
27 |
|
28 |
|
29 | wss.on('connection', function (client) {
|
30 | debug('New connection')
|
31 |
|
32 |
|
33 |
|
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 |
|
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 |
|
54 | return
|
55 | }
|
56 |
|
57 | client.send('ack ' + tuple[1])
|
58 | })
|
59 | })
|
60 |
|
61 |
|
62 | client.on('ping', function () {
|
63 | client.pong()
|
64 | })
|
65 | })
|
66 | }
|
67 |
|
68 | WsServer.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 | }
|