jykim16
9/7/2017 - 5:54 PM

subscribe publish module

subscribe publish module


let messageBus = {};
class Channel{
  constructor() {
    this.topicSubscriptionCache = {};
  }
  publish(topic, payload) {
    if (payload) {
      //find array of callbacks for topic in cache
      if(this.topicSubscriptionCache[topic]) {
        this.topicSubscriptionCache[topic].forEach((func)=>{
        //execute each callback in order. 
          func(payload);
        });
      }
    } else {
      if(this.topicSubscriptionCache[topic]) {
        this.topicSubscriptionCache[topic].forEach((func)=>{
        //execute each callback in order. 
          func();
        });
      }
    }
  }
  subscribe(topic, callback) {
    if(!this.topicSubscriptionCache[topic]) {
      this.topicSubscriptionCache[topic] = []; 
    };
    //push callback to key value. 
    this.topicSubscriptionCache[topic].push(callback);
  }
}
let channelCache = {general: new Channel()};

messageBus.subscribe = (...args) => {
  let channel = 'general', topic, callback;
  args.forEach((arg, i)=>{
    if (typeof arg === 'object') {
      arg.topic ? topic = arg.topic : topic;
      arg.channel ? channel = arg.channel : channel;
      arg.callback ? callback = arg.callback : callback;
    } else if (i === 0 && typeof arg !== 'object') {
      topic = arg;
    } else if (i === 1 && typeof arg !== 'object') {
      callback = arg;
    } 
  });
  //push callback to key value. 
  if(!channelCache[channel]) {
    channelCache[channel] = new Channel();
  }
  channelCache[channel].subscribe(topic, callback); 
};

messageBus.publish = (...args) => {
  let channel = 'general', topic, data;
  args.forEach((arg, i)=>{
    if (arg.data && typeof arg === 'object') {
      arg.topic ? topic = arg.topic : topic;
      arg.channel ? channel = arg.channel : channel;
      arg.data ? data = arg.data : data;
    } else if (i === 0 && typeof arg !== 'object') {
      topic = arg;
    } else if (i === 1 && typeof arg.data !== 'object') {
      data = arg;
    } 
  });
  if(channelCache[channel]) {
    channelCache[channel].publish(topic, data); 
  }
};

//tests
messageBus.subscribe('new_signup', function(payload) {
	console.log(payload)
});
messageBus.publish('new_signup', {'foo': 'bar', 'goo': 'gar'} );

messageBus.subscribe({
	channel: 'commerce',
	topic: 'order_complete',
	callback: function(payload) {
		console.log(payload)
	}
});
messageBus.subscribe({
	channel: 'commerce',
	topic: 'order_complete',
	callback: function(payload) {
		console.log('hi')
	}
});

messageBus.publish({
	channel: 'commerce',
	topic: 'order_complete',
	data: {
	  plan_level: 'GOLD',
	  user_id: '4273984723428'
	}
});