This repository has been archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
pubsub.js
91 lines (72 loc) · 2.23 KB
/
pubsub.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
'use strict'
const promisify = require('promisify-es6')
const setImmediate = require('async/setImmediate')
const OFFLINE_ERROR = require('../utils').OFFLINE_ERROR
module.exports = function pubsub (self) {
return {
subscribe: (topic, options, handler, callback) => {
if (!self.isOnline()) {
throw new Error(OFFLINE_ERROR)
}
if (typeof options === 'function') {
callback = handler
handler = options
options = {}
}
function subscribe (cb) {
if (self._pubsub.listenerCount(topic) === 0) {
self._pubsub.subscribe(topic)
}
self._pubsub.on(topic, handler)
setImmediate(() => callback())
}
if (!callback) {
return new Promise((resolve, reject) => {
subscribe((err) => {
if (err) {
return reject(err)
}
resolve()
})
})
} else {
subscribe(callback)
}
},
unsubscribe: (topic, handler) => {
self._pubsub.removeListener(topic, handler)
if (self._pubsub.listenerCount(topic) === 0) {
self._pubsub.unsubscribe(topic)
}
},
publish: promisify((topic, data, callback) => {
if (!self.isOnline()) {
return setImmediate(() => callback(new Error(OFFLINE_ERROR)))
}
if (!Buffer.isBuffer(data)) {
return setImmediate(() => callback(new Error('data must be a Buffer')))
}
self._pubsub.publish(topic, data)
setImmediate(() => callback())
}),
ls: promisify((callback) => {
if (!self.isOnline()) {
return setImmediate(() => callback(new Error(OFFLINE_ERROR)))
}
const subscriptions = Array.from(self._pubsub.subscriptions)
setImmediate(() => callback(null, subscriptions))
}),
peers: promisify((topic, callback) => {
if (!self.isOnline()) {
return setImmediate(() => callback(new Error(OFFLINE_ERROR)))
}
const peers = Array.from(self._pubsub.peers.values())
.filter((peer) => peer.topics.has(topic))
.map((peer) => peer.info.id.toB58String())
setImmediate(() => callback(null, peers))
}),
setMaxListeners (n) {
return self._pubsub.setMaxListeners(n)
}
}
}