-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubsub.js
67 lines (54 loc) · 1.54 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const redis = require('ioredis')
const CHANNELS = {
TEST: 'TEST',
BLOCKCHAIN: 'BLOCKCHAIN',
TRANSACTION: 'TRANSACTION'
};
class PubSub {
constructor({ blockchain, transactionPool, redisUrl }) {
this.blockchain = blockchain;
this.transactionPool = transactionPool;
this.publisher = redis.createClient(redisUrl);
this.subscriber = redis.createClient(redisUrl);
this.subscribeToChannels();
this.subscriber.on(
'message',
(channel, message) => this.handleMessage(channel, message)
);
}
subscribeToChannels() {
Object.values(CHANNELS).forEach(channel => {
this.subscriber.subscribe(channel);
});
}
handleMessage(channel, message) {
console.log(`Message received... Channel: ${channel}. Message: ${message}.`)
const parsedMessage = JSON.parse(message);
switch(channel) {
case CHANNELS.blockchain:
this.blockchain.replaceChain(parsedMessage, () => {
this.transactionPool.clearBlockchainTransactions({
chain: parsedMessage
});
});
case CHANNELS.subscription:
this.transactionPool.setTransaction(parsedMessage);
default:
return;
}
}
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;