feat: add EventEmitter to Emitter and singleton paradigm

Signed-off-by: Remi Cattiau <remi@cattiau.com>
This commit is contained in:
Remi Cattiau 2020-11-11 16:22:01 -08:00 committed by Lance Ball
parent 875f70017a
commit 25f9c48601
2 changed files with 53 additions and 0 deletions

View File

@ -1,4 +1,5 @@
import { v4 as uuidv4 } from "uuid"; import { v4 as uuidv4 } from "uuid";
import { Emitter } from "..";
import { import {
CloudEventV03, 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 * Clone a CloudEvent with new/update attributes
* @param {object} options attributes to augment the CloudEvent with * @param {object} options attributes to augment the CloudEvent with

View File

@ -1,5 +1,6 @@
import { CloudEvent } from "../event/cloudevent"; import { CloudEvent } from "../event/cloudevent";
import { HTTP, Message, Mode } from "../message"; import { HTTP, Message, Mode } from "../message";
import { EventEmitter } from "events";
/** /**
* Options is an additional, optional dictionary of options that may * 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);
}
}