|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const promisify = require('promisify-es6') |
| 4 | +const setImmediate = require('async/setImmediate') |
| 5 | + |
| 6 | +const OFFLINE_ERROR = require('../utils').OFFLINE_ERROR |
| 7 | + |
| 8 | +module.exports = function pubsub (self) { |
| 9 | + return { |
| 10 | + subscribe: (topic, options, handler, callback) => { |
| 11 | + if (!self.isOnline()) { |
| 12 | + throw OFFLINE_ERROR |
| 13 | + } |
| 14 | + |
| 15 | + if (typeof options === 'function') { |
| 16 | + callback = handler |
| 17 | + handler = options |
| 18 | + options = {} |
| 19 | + } |
| 20 | + |
| 21 | + if (!callback) { |
| 22 | + return new Promise((resolve, reject) => { |
| 23 | + subscribe(topic, options, handler, (err) => { |
| 24 | + if (err) { |
| 25 | + return reject(err) |
| 26 | + } |
| 27 | + resolve() |
| 28 | + }) |
| 29 | + }) |
| 30 | + } |
| 31 | + |
| 32 | + subscribe(topic, options, handler, callback) |
| 33 | + }, |
| 34 | + |
| 35 | + unsubscribe: (topic, handler) => { |
| 36 | + const ps = self._pubsub |
| 37 | + |
| 38 | + ps.removeListener(topic, handler) |
| 39 | + |
| 40 | + if (ps.listenerCount(topic) === 0) { |
| 41 | + ps.unsubscribe(topic) |
| 42 | + } |
| 43 | + }, |
| 44 | + |
| 45 | + publish: promisify((topic, data, callback) => { |
| 46 | + if (!self.isOnline()) { |
| 47 | + return setImmediate(() => callback(OFFLINE_ERROR)) |
| 48 | + } |
| 49 | + |
| 50 | + if (!Buffer.isBuffer(data)) { |
| 51 | + return setImmediate(() => callback(new Error('data must be a Buffer'))) |
| 52 | + } |
| 53 | + |
| 54 | + self._pubsub.publish(topic, data) |
| 55 | + setImmediate(() => callback()) |
| 56 | + }), |
| 57 | + |
| 58 | + ls: promisify((callback) => { |
| 59 | + if (!self.isOnline()) { |
| 60 | + return setImmediate(() => callback(OFFLINE_ERROR)) |
| 61 | + } |
| 62 | + |
| 63 | + const subscriptions = Array.from( |
| 64 | + self._pubsub.subscriptions |
| 65 | + ) |
| 66 | + |
| 67 | + setImmediate(() => callback(null, subscriptions)) |
| 68 | + }), |
| 69 | + |
| 70 | + peers: promisify((topic, callback) => { |
| 71 | + if (!self.isOnline()) { |
| 72 | + return setImmediate(() => callback(OFFLINE_ERROR)) |
| 73 | + } |
| 74 | + |
| 75 | + const peers = Array.from(self._pubsub.peers.values()) |
| 76 | + .filter((peer) => peer.topics.has(topic)) |
| 77 | + .map((peer) => peer.info.id.toB58String()) |
| 78 | + |
| 79 | + setImmediate(() => callback(null, peers)) |
| 80 | + }), |
| 81 | + |
| 82 | + setMaxListeners (n) { |
| 83 | + return self._pubsub.setMaxListeners(n) |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + function subscribe (topic, options, handler, callback) { |
| 88 | + const ps = self._pubsub |
| 89 | + |
| 90 | + if (ps.listenerCount(topic) === 0) { |
| 91 | + ps.subscribe(topic) |
| 92 | + } |
| 93 | + |
| 94 | + ps.on(topic, handler) |
| 95 | + setImmediate(() => callback()) |
| 96 | + } |
| 97 | +} |
0 commit comments