feat: add EventEmitter to Emitter and singleton paradigm
Signed-off-by: Remi Cattiau <remi@cattiau.com>
This commit is contained in:
parent
875f70017a
commit
25f9c48601
|
@ -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
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue