-
Notifications
You must be signed in to change notification settings - Fork 0
/
publishsuscribe.js
43 lines (37 loc) · 1.2 KB
/
publishsuscribe.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
const redis = require('redis')
const CHANNELS = {
TEST:'TEST',
BLOCKCHAIN:"BLOCKCHAIN"
}
class PubSub{
constructor({blockchain}){
this.blockchain = blockchain;
this.publisher = redis.createClient();
this.subscriber = redis.createClient();
this.subscriber.subscribe(CHANNELS.TEST);
this.subscriber.subscribe(CHANNELS.BLOCKCHAIN);
this.subscriber.on('message',(channel,message) => this.handleMessage(channel,message))
}
handleMessage(channel,message){
console.log(`MessageReciever. Channel : ${channel} Message:${message}`)
const parseMessage = JSON.parse(message)
if(channel === CHANNELS.BLOCKCHAIN){
this.blockchain.replaceChain(parseMessage)
}
}
publish({channel,message}){
this.publisher.publish(channel,message)
}
broadcastChain(){
this.publish({
channel:CHANNELS.BLOCKCHAIN,
message:JSON.stringify(this.blockchain.chain)
})
}
}
// const checkPubSub = new PubSub();
// setTimeout(
// () => checkPubSub.publisher.publish(CHANNELS.TEST, "Helllooooo"),
// 1000
// );
module.exports = PubSub;