@sailboat-computer/data-storage
Version:
Shared data storage library for sailboat computer v3
99 lines • 2.83 kB
JavaScript
;
/**
* Event Bus for Data Storage
*
* This module provides a simple event bus implementation for the data storage package.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.eventBus = exports.createEventBus = exports.InMemoryEventBus = exports.EventCategory = void 0;
// Define EventCategory constants
exports.EventCategory = {
DATA: 'category_data',
ALERT: 'category_alert',
CONFIGURATION: 'category_configuration',
SYSTEM: 'category_system',
USER_ACTION: 'category_user_action'
};
/**
* In-memory event bus implementation
*/
class InMemoryEventBus {
constructor() {
this.subscriptions = new Map();
}
/**
* Publish an event
*
* @param eventType - Event type
* @param data - Event data
* @param options - Event options
*/
async publish(eventType, data, options) {
const handlers = this.subscriptions.get(eventType);
if (!handlers) {
return;
}
const promises = [];
for (const handler of handlers.values()) {
try {
const result = handler(data);
if (result instanceof Promise) {
promises.push(result);
}
}
catch (error) {
console.error(`Error handling event ${eventType}:`, error);
}
}
if (promises.length > 0) {
await Promise.all(promises);
}
}
/**
* Subscribe to an event
*
* @param eventType - Event type
* @param handler - Event handler
* @returns Subscription ID
*/
subscribe(eventType, handler) {
if (!this.subscriptions.has(eventType)) {
this.subscriptions.set(eventType, new Map());
}
const subscriptionId = `${eventType}-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
this.subscriptions.get(eventType).set(subscriptionId, handler);
return subscriptionId;
}
/**
* Unsubscribe from an event
*
* @param subscriptionId - Subscription ID
*/
unsubscribe(subscriptionId) {
const [eventType] = subscriptionId.split('-');
if (!eventType) {
return;
}
const handlers = this.subscriptions.get(eventType);
if (!handlers) {
return;
}
handlers.delete(subscriptionId);
if (handlers.size === 0) {
this.subscriptions.delete(eventType);
}
}
}
exports.InMemoryEventBus = InMemoryEventBus;
/**
* Create a new event bus
*
* @returns Event bus
*/
function createEventBus() {
return new InMemoryEventBus();
}
exports.createEventBus = createEventBus;
// Export singleton instance
exports.eventBus = createEventBus();
//# sourceMappingURL=index.js.map