Ghost/ghost/domain-events/lib/DomainEvents.js
Fabien O'Carroll 6c01ff2a3d Added @tryghost/domain-events package
refs https://github.com/TryGhost/Team/issues/1054

This package will be used as a singleton for listenig and sending events
throughout the members application.
2021-09-17 15:22:08 +02:00

45 lines
887 B
JavaScript

const EventEmitter = require('events').EventEmitter;
/**
* @template T
* @typedef {import('./').ConstructorOf<T>} ConstructorOf<T>
*/
/**
* @template Data
* @typedef {object} IEvent
* @prop {Date} timestamp
* @prop {Data} data
*/
class DomainEvents {
/**
* @private
* @type EventEmitter
*/
static ee = new EventEmitter;
/**
* @template Data
* @template {IEvent<Data>} EventClass
* @param {ConstructorOf<EventClass>} Event
* @param {(event: EventClass) => void} handler
*
* @returns {void}
*/
static subscribe(Event, handler) {
DomainEvents.ee.on(Event.name, handler);
}
/**
* @template Data
* @param {IEvent<Data>} event
* @returns {void}
*/
static dispatch(event) {
DomainEvents.ee.emit(event.constructor.name, event);
}
}
module.exports = DomainEvents;