Created
December 6, 2018 21:17
-
-
Save dheerajsuthar/f9668e9a6a2c36d36f58bca1f3efec6f to your computer and use it in GitHub Desktop.
Publisher Subscriber Manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PubSubManager { | |
constructor() { | |
this.channels = { | |
weather: { | |
message: '', | |
subscribers: [] | |
}, | |
sports: { | |
message: '', | |
subscribers: [] | |
} | |
} | |
this.brokerId = setInterval(() => { this.broker() }, 1000); | |
} | |
subscribe(subscriber, channel) { | |
console.log(`subscribing to ${channel}`); | |
this.channels[channel].subscribers.push(subscriber); | |
} | |
removeBroker() { | |
clearInterval(this.brokerId); | |
} | |
publish(publisher, channel, message) { | |
this.channels[channel].message = message; | |
} | |
broker() { | |
for (const channel in this.channels) { | |
if (this.channels.hasOwnProperty(channel)) { | |
const channelObj = this.channels[channel]; | |
if (channelObj.message) { | |
console.log(`found message: ${channelObj.message} in ${channel}`); | |
channelObj.subscribers.forEach(subscriber => { | |
subscriber.send(JSON.stringify({ | |
message: channelObj.message | |
})); | |
}); | |
channelObj.message = ''; | |
} | |
} | |
} | |
} | |
} | |
module.exports = PubSubManager; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think the broker key loop can use
Object.getOwnPropertyNames
.