Skip to content

fix: parse JSON data of binary MQTT messages - #683

Open
rida-ghreizy wants to merge 1 commit into
cloudevents:mainfrom
rida-ghreizy:fix/mqtt-binary-json-data
Open

rida-ghreizy wants to merge 1 commit into
cloudevents:mainfrom
rida-ghreizy:fix/mqtt-binary-json-data

Conversation

@rida-ghreizy

Copy link
Copy Markdown

Proposed Changes

In binary mode, the HTTP and Kafka bindings parse the event data when the content type is application/json. The MQTT binding passed the payload through unchanged. An MQTT client receives the payload as bytes (a Buffer) or a string, so an event sent with JSON data came back with data as a string or a Buffer instead of an object:

const ev = new CloudEvent({ source: "/d", type: "t", datacontenttype: "application/json", data: { a: 1 } });
// payload as received from the broker
HTTP.toEvent(...).data   // { a: 1 }
Kafka.toEvent(...).data  // { a: 1 }
MQTT.toEvent(...).data   // before: '{"a":1}'   after: { a: 1 }

This PR adds extractBinaryData to the MQTT binding, mirroring the Kafka one. When the event's datacontenttype, or the PUBLISH Content Type if that is missing, starts with application/json, and the payload is a string or a Buffer, it is parsed as JSON. Payloads that are already objects, other content types, and text that isn't valid JSON are returned unchanged, so existing callers that pass objects don't change.

Description

New tests in test/integration/mqtt_tests.ts:

  • JSON data received as a Buffer and as a string is parsed;
  • text that isn't valid JSON is kept as it was.

Without the change the first test fails. With it, the full suite passes (npx mocha --exit --require ts-node/register ./test/integration/**/*.ts: 236 passing), and ESLint is clean on the changed files.

The HTTP and Kafka bindings parse binary event data with a JSON content
type, but the MQTT binding returned the payload as received, so JSON
data came back as a string or Buffer. Parse string and Buffer payloads
when the content type is application/json, keeping other payloads as
they are.

Signed-off-by: rida <ghreizyrida1@gmail.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant