@@ -98,7 +98,7 @@ export class Emitter extends EventEmitter {
9898 /**
9999 * Singleton store
100100 */
101- static singleton : Emitter | undefined = undefined ;
101+ static instance : Emitter | undefined = undefined ;
102102 url ?: string ;
103103 protocol : Protocol ;
104104 binaryEmitter : EmitterFunction ;
@@ -113,7 +113,9 @@ export class Emitter extends EventEmitter {
113113 * @param {Object } [options] The configuration options for this event. Options
114114 * provided will be passed along to Node.js `http.request()`.
115115 * https://nodejs.org/api/http.html#http_http_request_options_callback
116- * @deprecated Will be removed in 4.0.0. Consider using the emitterFactory
116+ * @deprecated in 4.0.0 this class functionality will be limited to events propagated
117+ * throughout the Node.js process. To emit events over a transport protocol, consider using the
118+ * emitterFactory
117119 */
118120 constructor ( options : TransportOptions = { protocol : Protocol . HTTPBinary } ) {
119121 super ( ) ;
@@ -153,20 +155,42 @@ export class Emitter extends EventEmitter {
153155 *
154156 * @return {Emitter } return Emitter singleton
155157 */
156- static getSingleton ( ) : Emitter {
157- if ( ! Emitter . singleton ) {
158- Emitter . singleton = new Emitter ( ) ;
158+ static getInstance ( ) : Emitter {
159+ if ( ! Emitter . instance ) {
160+ Emitter . instance = new Emitter ( ) ;
159161 }
160- return Emitter . singleton ;
162+ return Emitter . instance ;
163+ }
164+
165+ /**
166+ * Add a listener for eventing
167+ *
168+ * @param {string } event type to listen to
169+ * @param {Function } listener to call on event
170+ * @return {void }
171+ */
172+ static on ( event : "cloudevent" | "newListener" | "removeListener" , listener : ( ...args : any [ ] ) => void ) : void {
173+ this . getInstance ( ) . on ( event , listener ) ;
161174 }
162175
163176 /**
164177 * Emit an event inside this application
165178 *
166179 * @param {CloudEvent } event to emit
180+ * @param {boolean } ensureDelivery fail the promise if one listener fail
167181 * @return {void }
168182 */
169- static emitEvent ( event : CloudEvent ) : void {
170- this . getSingleton ( ) . emit ( "event" , event ) ;
183+ static async emitEvent ( event : CloudEvent , ensureDelivery = false ) : Promise < void > {
184+ if ( ! ensureDelivery ) {
185+ // Ensure delivery is disabled so we don't wait for Promise
186+ Emitter . getInstance ( ) . emit ( "cloudevent" , event ) ;
187+ } else {
188+ // Execute all listeners and wrap them in a Promise
189+ await Promise . all (
190+ Emitter . getInstance ( )
191+ . listeners ( "cloudevent" )
192+ . map ( async ( l ) => l ( event ) ) ,
193+ ) ;
194+ }
171195 }
172196}
0 commit comments