Skip to content

Commit 02ad12c

Browse files
committed
src(message): adds Detector interface to ease detection of events
Fixes: #295 Signed-off-by: Lance Ball <[email protected]>
1 parent 038d73e commit 02ad12c

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

src/message/http/index.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,17 @@ export function structured(event: CloudEvent): Message {
2626
};
2727
}
2828

29+
// implements Detector
30+
// TODO: this could probably be optimized
31+
export function isEvent(message: Message): boolean {
32+
try {
33+
deserialize(message);
34+
return true;
35+
} catch (err) {
36+
return false;
37+
}
38+
}
39+
2940
/**
3041
* Converts a Message to a CloudEvent
3142
*

src/message/index.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { CloudEvent } from "..";
2-
import { binary, deserialize, structured } from "./http";
2+
import { binary, deserialize, structured, isEvent } from "./http";
33
import { headersFor } from "./http/headers";
44

55
/**
@@ -11,6 +11,7 @@ export interface Binding {
1111
binary: Serializer;
1212
structured: Serializer;
1313
toEvent: Deserializer;
14+
isEvent: Detector;
1415
}
1516

1617
/**
@@ -54,11 +55,20 @@ export interface Deserializer {
5455
(message: Message): CloudEvent;
5556
}
5657

58+
/**
59+
* Detector is a function interface that detects whether
60+
* a message contains a valid CloudEvent
61+
*/
62+
export interface Detector {
63+
(message: Message): boolean;
64+
}
65+
5766
// HTTP Message capabilities
5867
export const HTTP: Binding = {
5968
binary: binary as Serializer,
6069
structured: structured as Serializer,
6170
toEvent: deserialize as Deserializer,
71+
isEvent: isEvent as Detector,
6272
};
6373

6474
// TODO: Deprecated. Remove this for 4.0

test/integration/message_test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,26 @@ const dataBinary = Uint32Array.from(JSON.stringify(data), (c) => c.codePointAt(0
2828
const data_base64 = asBase64(dataBinary);
2929

3030
describe("HTTP transport messages", () => {
31+
it("can detect CloudEvent Messages", () => {
32+
// Create a message that is not an actual event
33+
let message: Message = {
34+
body: "Hello world!",
35+
headers: {
36+
"Content-type": "text/plain",
37+
},
38+
};
39+
expect(HTTP.isEvent(message)).to.be.false;
40+
41+
// Now create a message that is an event
42+
message = HTTP.binary(
43+
new CloudEvent({
44+
source: "/message-test",
45+
type: "example",
46+
}),
47+
);
48+
expect(HTTP.isEvent(message)).to.be.true;
49+
});
50+
3151
describe("Specification version V1", () => {
3252
const fixture: CloudEvent = new CloudEvent({
3353
specversion: Version.V1,

0 commit comments

Comments
 (0)