-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpublish_subscribe.js
45 lines (41 loc) · 1.09 KB
/
publish_subscribe.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
const redis = require("redis");
const channel = {
test: "test",
blockchain: "blockchain",
};
class PubSub {
constructor({ blockchain }) {
this.publisher = redis.createClient();
this.subscriber = redis.createClient();
this.blockchain = blockchain;
this.subscriber.subscribe(channel.test);
this.subscriber.subscribe(channel.blockchain);
this.subscriber.on("message", (c, message) => {
this.handleMessage(c, message);
});
}
handleMessage(c, message) {
console.log(
`Message recieved on channel : ${c} and the Message : ${message}`
);
const parseMessage = JSON.parse(message);
if (c === channel.blockchain) {
this.blockchain.replaceChain(parseMessage);
}
}
publish({ c, message }) {
this.publisher.publish(c, message);
}
broadcastChain() {
this.publish({
channel: channel.blockchain,
message: JSON.stringify(this.blockchain.chain),
});
}
}
// const checkPubSub = new PubSub();
// setTimeout(
// () => checkPubSub.publisher.publish(channel.test, "Hello channel"),
// 1000
// );
module.exports = PubSub;