Skip to content

Commit e32f292

Browse files
committed
feat: add EventEmitter to Emitter and singleton paradigm
1 parent 765b81c commit e32f292

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

src/event/cloudevent.ts

Lines changed: 9 additions & 0 deletions
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,14 @@ export class CloudEvent implements CloudEventV1, CloudEventV03 {
167168
}
168169
}
169170

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

src/transport/emitter.ts

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,15 +91,29 @@ export function emitterFor(fn: TransportFunction, options = { binding: HTTP, mod
9191
*
9292
* @see https://github.com/cloudevents/spec/blob/v1.0/http-protocol-binding.md
9393
* @see https://github.com/cloudevents/spec/blob/v1.0/http-protocol-binding.md#13-content-modes
94-
* @deprecated Will be removed in 4.0.0. Consider using the emitterFactory
9594
*
9695
*/
97-
export class Emitter {
96+
export class Emitter extends EventEmitter {
97+
/**
98+
* Singleton store
99+
*/
100+
static singleton: Emitter = undefined;
98101
url?: string;
99102
protocol: Protocol;
100103
binaryEmitter: EmitterFunction;
101104
structuredEmitter: EmitterFunction;
102105

106+
/**
107+
* Create an Emitter
108+
* On v4.0.0 this class will only remains as Singleton to allow using the
109+
* EventEmitter of NodeJS
110+
*
111+
*
112+
* @param {Object} [options] The configuration options for this event. Options
113+
* provided will be passed along to Node.js `http.request()`.
114+
* https://nodejs.org/api/http.html#http_http_request_options_callback
115+
* @deprecated Will be removed in 4.0.0. Consider using the emitterFactory
116+
*/
103117
constructor(options: TransportOptions = { protocol: Protocol.HTTPBinary }) {
104118
this.protocol = options.protocol as Protocol;
105119
this.url = options.url;
@@ -131,4 +145,23 @@ export class Emitter {
131145
}
132146
return this.binaryEmitter(event, options);
133147
}
148+
149+
/**
150+
* Return or create the Emitter singleton
151+
*/
152+
static getSingleton() {
153+
if (!Emitter.singleton) {
154+
Emitter.singleton = new Emitter();
155+
}
156+
return Emitter.singleton;
157+
}
158+
159+
/**
160+
* Emit an event inside this application
161+
*
162+
* @param event to emit
163+
*/
164+
static emit(event: CloudEvent) {
165+
this.getSingleton().emit("event", event);
166+
}
134167
}

0 commit comments

Comments
 (0)