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