Skip to content

Commit 25f9c48

Browse files
loopingzlance
authored andcommitted
feat: add EventEmitter to Emitter and singleton paradigm
Signed-off-by: Remi Cattiau <remi@cattiau.com>
1 parent 875f700 commit 25f9c48

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

Diff for: src/event/cloudevent.ts

+11
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { v4 as uuidv4 } from "uuid";
2+
import { Emitter } from "..";
23

34
import {
45
CloudEventV03,
@@ -167,6 +168,16 @@ export class CloudEvent implements CloudEventV1, CloudEventV03 {
167168
}
168169
}
169170

171+
/**
172+
* Emit this CloudEvent through the application
173+
*
174+
* @return {CloudEvent} current CloudEvent object
175+
*/
176+
public emit(): this {
177+
Emitter.emitEvent(this);
178+
return this;
179+
}
180+
170181
/**
171182
* Clone a CloudEvent with new/update attributes
172183
* @param {object} options attributes to augment the CloudEvent with

Diff for: src/transport/emitter.ts

+42
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { CloudEvent } from "../event/cloudevent";
22
import { HTTP, Message, Mode } from "../message";
3+
import { EventEmitter } from "events";
34

45
/**
56
* Options is an additional, optional dictionary of options that may
@@ -58,3 +59,44 @@ export function emitterFor(fn: TransportFunction, options = { binding: HTTP, mod
5859
}
5960
};
6061
}
62+
63+
/**
64+
* A static class to emit CloudEvents within an application
65+
*/
66+
export class Emitter extends EventEmitter {
67+
/**
68+
* Singleton store
69+
*/
70+
static singleton: Emitter | undefined = undefined;
71+
72+
/**
73+
* Create an Emitter
74+
* On v4.0.0 this class will only remains as Singleton to allow using the
75+
* EventEmitter of NodeJS
76+
*/
77+
private constructor() {
78+
super();
79+
}
80+
81+
/**
82+
* Return or create the Emitter singleton
83+
*
84+
* @return {Emitter} return Emitter singleton
85+
*/
86+
static getSingleton(): Emitter {
87+
if (!Emitter.singleton) {
88+
Emitter.singleton = new Emitter();
89+
}
90+
return Emitter.singleton;
91+
}
92+
93+
/**
94+
* Emit an event inside this application
95+
*
96+
* @param {CloudEvent} event to emit
97+
* @return {void}
98+
*/
99+
static emitEvent(event: CloudEvent): void {
100+
this.getSingleton().emit("event", event);
101+
}
102+
}

0 commit comments

Comments
 (0)