diff --git a/lib/bindings/http/http_receiver.js b/lib/bindings/http/http_receiver.js index 09128642..866c7966 100644 --- a/lib/bindings/http/http_receiver.js +++ b/lib/bindings/http/http_receiver.js @@ -2,7 +2,14 @@ const V03Binary = require("./receiver_binary_0_3"); const V03Structured = require("./receiver_structured_0_3.js"); const V1Binary = require("./receiver_binary_1.js"); const V1Structured = require("./receiver_structured_1.js"); -const constants = require("./constants"); +const { + SPEC_V03, + SPEC_V1, + HEADER_CONTENT_TYPE, + MIME_CE, + BINARY_HEADERS_1, + DEFAULT_SPEC_VERSION_HEADER +} = require("./constants"); class HTTPReceiver { constructor() { @@ -22,33 +29,37 @@ class HTTPReceiver { const mode = getMode(headers); const version = getVersion(mode, headers, body); switch (version) { - case constants.SPEC_V1: + case SPEC_V1: return this.receivers.v1[mode].parse(body, headers); - case constants.SPEC_V03: + case SPEC_V03: return this.receivers.v03[mode].parse(body, headers); default: console.error( - `Unknown spec version ${version}. Default to ${constants.SPEC_V1}`); + `Unknown spec version ${version}. Default to ${SPEC_V1}`); return this.receivers.v1[mode].parse(body, headers); } } } function getMode(headers) { - let mode = "binary"; - const contentType = headers[constants.HEADER_CONTENT_TYPE]; - if (contentType && contentType.startsWith(constants.MIME_CE)) { + let mode = "unknown"; + const contentType = headers[HEADER_CONTENT_TYPE]; + if (contentType && contentType.startsWith(MIME_CE)) { mode = "structured"; + } else if (headers[BINARY_HEADERS_1.ID]) { + mode = "binary"; + } else { + throw new TypeError("no cloud event detected"); } return mode; } function getVersion(mode, headers, body) { - let version = constants.SPEC_V1; // default to 1.0 + let version = SPEC_V1; // default to 1.0 if (mode === "binary") { // Check the headers for the version - const versionHeader = headers[constants.DEFAULT_SPEC_VERSION_HEADER]; + const versionHeader = headers[DEFAULT_SPEC_VERSION_HEADER]; if (versionHeader) { version = versionHeader; } } else { // structured mode - the version is in the body diff --git a/test/bindings/http/promiscuous_receiver_test.js b/test/bindings/http/promiscuous_receiver_test.js index e99aa3cb..17ab81c7 100644 --- a/test/bindings/http/promiscuous_receiver_test.js +++ b/test/bindings/http/promiscuous_receiver_test.js @@ -18,6 +18,22 @@ const data = { }; describe("HTTP Transport Binding Receiver for CloudEvents", () => { + describe("HTTP CloudEvent format detection", () => { + const specversion = "1.0"; + it("Throws when the event format cannot be detected", () => { + const payload = { + id, + type, + source, + data, + specversion + }; + + expect(receiver.accept.bind(receiver, {}, payload)) + .to.throw("no cloud event detected"); + }); + }); + describe("V1", () => { const specversion = "1.0";