-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsub.js
50 lines (39 loc) · 1.15 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
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.subscribeToChannel();
this.subscriber.on('message', (channel, message) =>
this.handleMessage(channel, message)
);
}
handleMessage(channel, message) {
console.log(`Message received. Channel: ${channel}. Message: ${message}`);
const parsedMessage = JSON.parse(message);
if (channel === CHANNELS.BLOCKCHAIN) {
this.blockchain.replaceChain(parsedMessage);
}
}
subscribeToChannel() {
Object.values(CHANNELS).forEach(channel => {
this.subscriber.subscribe(channel);
});
}
publish({ channel, message }) {
this.subscriber.unsubscribe(channel, () => {
this.publisher.publish(channel, message, () => {
this.subscriber.subscribe(channel);
});
});
}
broadcastChain() {
this.publish({
channel: CHANNELS.BLOCKCHAIN,
message: JSON.stringify(this.blockchain.chain)
});
}
}
module.exports = PubSub;