UNPKG

communication-bus

Version:

Publisher subscriber library for communication in JS across components

42 lines (31 loc) 1.17 kB
import Subscribers from "./subscribers"; import Validator from "./validator"; import EventSchemaMap from "./schema"; const publishedEvents = []; const publish = (eventName, data = {}) => { if (!eventName) throw new Error("Event name is required"); const schema = EventSchemaMap[eventName]; if (!schema) throw new Error(`${eventName} is not registered`); const isValid = Validator.validate(data, schema); if (!isValid) throw new Error("Event data failed to match the schema"); Subscribers.getOrderedSubscribers().map(callback => { try { callback(eventName, data); } catch (e) {} }); publishedEvents.push({ eventName, data }); }; const rePublishEventForSubscriber = (subscriberId, offset = 0) => { if (!subscriberId) throw new Error("SubscriberId is required"); if (offset < 1) throw new Error("Offset value must be greater than 0"); if (publishedEvents.length < 1) return false; let i = publishedEvents.length - offset; i = i < 0 ? 0 : i; for (; i < publishedEvents.length; i++) { Subscribers.getSubscriberById(subscriberId)(publishedEvents[i]); } }; export default { publish, rePublishEventForSubscriber };