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