UNPKG

@sprucelabs/spruce-event-utils

Version:

Some helpful utilities to speed up working with Mercury! 🚅

59 lines (58 loc) • 2.27 kB
import { EVENT_VERSION_DIVIDER } from '../constants.js'; const splitCache = {}; const eventNameUtil = { split(name) { if (!splitCache[name]) { const versionParts = name.split('::'); const fullyQualifiedEventName = versionParts[0]; const version = versionParts[1]; const parts = fullyQualifiedEventName.split('.'); const eventNamespace = parts[1] ? parts[0] : undefined; const eventName = parts[1] || parts[0]; const e = { eventName, }; if (eventNamespace) { e.eventNamespace = eventNamespace; } if (version) { e.version = version; } splitCache[name] = e; } return splitCache[name]; }, join(options) { const { eventName: eventNameOptions, eventNamespace: eventNamespaceOptions, version: versionOptions, } = options; let { eventName, eventNamespace, version } = this.split(eventNameOptions); eventNamespace = eventNamespaceOptions !== null && eventNamespaceOptions !== void 0 ? eventNamespaceOptions : eventNamespace; version = versionOptions !== null && versionOptions !== void 0 ? versionOptions : version; function optionallyAttachversion(name) { if (version) { return name + EVENT_VERSION_DIVIDER + version; } return name; } if (!eventNamespace) { return optionallyAttachversion(eventName); } let fullyQualifiedEventName = !eventNamespace ? eventName : `${eventNamespace}.${eventName.replace(eventNamespace + '.', '')}`; fullyQualifiedEventName = optionallyAttachversion(fullyQualifiedEventName); return fullyQualifiedEventName; }, generateResponseEventName(fullyQualifiedEventName) { const { eventName, eventNamespace, version } = this.split(fullyQualifiedEventName); let name = `${this.join({ eventNamespace, eventName, version: '', })}:response`; if (version) { name += '::' + version; } return name; }, }; export default eventNameUtil;