UNPKG

1.2 kBJavaScriptView Raw
1'use strict'
2
3const pull = require('pull-stream')
4const EventEmitter = require('events')
5
6const emitter = new EventEmitter()
7
8function handler (protocol, conn) {
9 conn.getPeerInfo((err, peerInfo) => {
10 if (err) {
11 console.log(err)
12 return
13 }
14
15 const peerId = peerInfo.id.toB58String()
16
17 pull(
18 conn,
19 pull.map((message) => {
20 let msg
21 try {
22 msg = JSON.parse(message.toString())
23 } catch (err) {
24 emitter.emit('warning', err.message)
25 return // early
26 }
27
28 if (peerId !== msg.from) {
29 emitter.emit('warning', 'no peerid match ' + msg.from)
30 return // early
31 }
32
33 const topicIDs = msg.topicIDs
34 if (!Array.isArray(topicIDs)) {
35 emitter.emit('warning', 'no topic IDs')
36 return // early
37 }
38
39 msg.data = Buffer.from(msg.data, 'hex')
40 msg.seqno = Buffer.from(msg.seqno, 'hex')
41
42 topicIDs.forEach((topic) => {
43 emitter.emit(topic, msg)
44 })
45
46 return msg
47 }),
48 pull.onEnd(() => {
49 // do nothing
50 })
51 )
52 })
53}
54
55exports = module.exports = {
56 handler: handler,
57 emitter: emitter
58}