-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpublishsubscribe.js
49 lines (39 loc) · 1.18 KB
/
publishsubscribe.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
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(`Message recieved. 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);
}
brodcastChain(){
this.publish({
channel:CHANNELS.BLOCKCHAIN,
message: JSON.stringify(this.blockchain.chain),
});
}
}
// const check = new PubSub();
// setTimeout(
// () => check.publisher.publish(CHANNELS.TEST,"HELLLO"),
// 1000
// );
module.exports = PubSub;