@@ -9,7 +9,7 @@ import { Emitter } from "..";
99
1010import { CloudEventV1 } from "./interfaces" ;
1111import { validateCloudEvent } from "./spec" ;
12- import { ValidationError , isBinary , asBase64 , isValidType } from "./validation" ;
12+ import { ValidationError , isBinary , asBase64 , isValidType , base64AsBinary } from "./validation" ;
1313
1414/**
1515 * An enum representing the CloudEvent specification version
@@ -33,7 +33,7 @@ export class CloudEvent<T = undefined> implements CloudEventV1<T> {
3333 dataschema ?: string ;
3434 subject ?: string ;
3535 time ?: string ;
36- #_data ?: T ;
36+ data ?: T ;
3737 data_base64 ?: string ;
3838
3939 // Extensions should not exist as it's own object, but instead
@@ -85,12 +85,21 @@ export class CloudEvent<T = undefined> implements CloudEventV1<T> {
8585 delete properties . dataschema ;
8686
8787 this . data_base64 = properties . data_base64 as string ;
88+
89+ if ( this . data_base64 ) {
90+ this . data = base64AsBinary ( this . data_base64 ) as unknown as T ;
91+ }
92+
8893 delete properties . data_base64 ;
8994
9095 this . schemaurl = properties . schemaurl as string ;
9196 delete properties . schemaurl ;
9297
93- this . data = properties . data ;
98+ if ( isBinary ( properties . data ) ) {
99+ this . data_base64 = asBase64 ( properties . data as unknown as Buffer ) ;
100+ }
101+
102+ this . data = typeof properties . data !== "undefined" ? properties . data : this . data ;
94103 delete properties . data ;
95104
96105 // sanity checking
@@ -127,17 +136,6 @@ See: https://github.com/cloudevents/spec/blob/v1.0/spec.md#type-system`);
127136 Object . freeze ( this ) ;
128137 }
129138
130- get data ( ) : T | undefined {
131- return this . #_data;
132- }
133-
134- set data ( value : T | undefined ) {
135- if ( isBinary ( value ) ) {
136- this . data_base64 = asBase64 ( value as unknown as Buffer ) ;
137- }
138- this . #_data = value ;
139- }
140-
141139 /**
142140 * Used by JSON.stringify(). The name is confusing, but this method is called by
143141 * JSON.stringify() when converting this object to JSON.
@@ -147,7 +145,11 @@ See: https://github.com/cloudevents/spec/blob/v1.0/spec.md#type-system`);
147145 toJSON ( ) : Record < string , unknown > {
148146 const event = { ...this } ;
149147 event . time = new Date ( this . time as string ) . toISOString ( ) ;
150- event . data = this . #_data;
148+
149+ if ( event . data_base64 && event . data ) {
150+ delete event . data ;
151+ }
152+
151153 return event ;
152154 }
153155
@@ -230,9 +232,6 @@ See: https://github.com/cloudevents/spec/blob/v1.0/spec.md#type-system`);
230232 event : CloudEventV1 < any > ,
231233 options : Partial < CloudEventV1 < any > > ,
232234 strict = true ) : CloudEvent < any > {
233- if ( event instanceof CloudEvent ) {
234- event = event . toJSON ( ) as CloudEventV1 < any > ;
235- }
236235 return new CloudEvent ( Object . assign ( { } , event , options ) , strict ) ;
237236 }
238237}
0 commit comments