From 25f9c4860169a8ab576fba47791497ada3048d9f Mon Sep 17 00:00:00 2001 From: Remi Cattiau Date: Wed, 11 Nov 2020 16:22:01 -0800 Subject: [PATCH] feat: add EventEmitter to Emitter and singleton paradigm Signed-off-by: Remi Cattiau --- src/event/cloudevent.ts | 11 +++++++++++ src/transport/emitter.ts | 42 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/src/event/cloudevent.ts b/src/event/cloudevent.ts index e6322f8..eefa338 100644 --- a/src/event/cloudevent.ts +++ b/src/event/cloudevent.ts @@ -1,4 +1,5 @@ import { v4 as uuidv4 } from "uuid"; +import { Emitter } from ".."; import { CloudEventV03, @@ -167,6 +168,16 @@ export class CloudEvent implements CloudEventV1, CloudEventV03 { } } + /** + * Emit this CloudEvent through the application + * + * @return {CloudEvent} current CloudEvent object + */ + public emit(): this { + Emitter.emitEvent(this); + return this; + } + /** * Clone a CloudEvent with new/update attributes * @param {object} options attributes to augment the CloudEvent with diff --git a/src/transport/emitter.ts b/src/transport/emitter.ts index 9204e9a..019c6d3 100644 --- a/src/transport/emitter.ts +++ b/src/transport/emitter.ts @@ -1,5 +1,6 @@ import { CloudEvent } from "../event/cloudevent"; import { HTTP, Message, Mode } from "../message"; +import { EventEmitter } from "events"; /** * Options is an additional, optional dictionary of options that may @@ -58,3 +59,44 @@ export function emitterFor(fn: TransportFunction, options = { binding: HTTP, mod } }; } + +/** + * A static class to emit CloudEvents within an application + */ +export class Emitter extends EventEmitter { + /** + * Singleton store + */ + static singleton: Emitter | undefined = undefined; + + /** + * Create an Emitter + * On v4.0.0 this class will only remains as Singleton to allow using the + * EventEmitter of NodeJS + */ + private constructor() { + super(); + } + + /** + * Return or create the Emitter singleton + * + * @return {Emitter} return Emitter singleton + */ + static getSingleton(): Emitter { + if (!Emitter.singleton) { + Emitter.singleton = new Emitter(); + } + return Emitter.singleton; + } + + /** + * Emit an event inside this application + * + * @param {CloudEvent} event to emit + * @return {void} + */ + static emitEvent(event: CloudEvent): void { + this.getSingleton().emit("event", event); + } +}