-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpublishsubscribe.js
More file actions
41 lines (34 loc) · 1.19 KB
/
Copy pathpublishsubscribe.js
File metadata and controls
41 lines (34 loc) · 1.19 KB
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
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);
}
broadcastChain(){
this.publish({
channnel:CHANNELS.BLOCKCHAIN,
message:JSON.stringify(this.blockchain.chain),
});
}
}
//const checkPubSub = new PubSub();
//setTimeout(() => checkPubSub.publisher.publish(CHANNELS.TEST, "Hiloo"), 1000);
module.exports = PubSub;