Last active
October 4, 2019 14:01
-
-
Save garryyao/665e3f9b37c4e19fa6fcd22e4df246c9 to your computer and use it in GitHub Desktop.
really simple SNS in javascript
This file contains hidden or 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
const SNS = require('./sns'); | |
const sns = new SNS(); | |
function smsSubscriber(data) { | |
console.log(`send sms for transaction: ${data.transactionId}`); | |
return 'sms'; | |
} | |
async function emailSubscriber(data) { | |
//await fetch('/email'); | |
console.log(`email sent for transaction: ${data.transactionId}`); | |
return 'email' | |
} | |
const sms1 = sns.subscribe('match', smsSubscriber); | |
const email2 = sns.subscribe('match', emailSubscriber); | |
const email3 = sns.subscribe('match', emailSubscriber); | |
//sns.unsubscribe('match', id2); | |
sns.unsubscribe('match', email3); | |
sns.publish('match', {transactionId: '123'}).then((retval) => { | |
console.log('all subscribers notified:', retval); | |
}); | |
const sms2 = sns.subscribe('match', smsSubscriber); | |
sns.publish('match', { transactionId: '456' }); | |
//console.log(sns.subscirbes); |
This file contains hidden or 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 SNS { | |
constructor() { | |
this.topics = {}; | |
} | |
createTopic(topic) { | |
return this.topics[topic] = { id: 0, lastPublishedData: null, subscribers: {}}; | |
} | |
subscribe(topic, fn) { | |
const t = this.topics[topic] || this.createTopic(topic); | |
// recall last published data | |
if(t.lastPublishedData) { | |
fn(t.lastPublishedData); | |
} | |
t.subscribers[t.id] = fn; | |
return t.id++; | |
} | |
unsubscribe(topic, id) { | |
let t = this.topics[topic]; | |
if (t) { | |
delete t.subscribers[id]; | |
} | |
} | |
publish(topic, data) { | |
let t = this.topics[topic]; | |
if (t) { | |
t.lastPublishedData = data; | |
return Promise.all(Object.values(t.subscribers).map((val) => val(data))); | |
} | |
} | |
} | |
module.exports = SNS; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment