Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion src/message/mqtt/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,35 @@ function toEvent<T>(message: Message<T>, strict = false): CloudEventV1<T> | Clou
} else {
return new CloudEvent<T>({
...message.headers,
data: message.body as T,
data: extractBinaryData(message as MQTTMessage<T>),
}, false);
}
}

/**
* Gets the data of a binary MQTT message. Like the HTTP and Kafka bindings, JSON data
* received as text (a string or a Buffer) is parsed.
* @param {MQTTMessage<T>} message a binary MQTTMessage
* @returns {T} the event data
*/
function extractBinaryData<T>(message: MQTTMessage<T>): T {
const body = message.body as unknown;
const contentType = (message.headers?.datacontenttype ?? message.PUBLISH?.["Content Type"]) as string | undefined;
if (!contentType || !contentType.startsWith(CONSTANTS.MIME_JSON)) {
return body as T;
}
const text = typeof body === "string" ? body : Buffer.isBuffer(body) ? body.toString() : undefined;
if (text === undefined) {
return body as T;
}
try {
return JSON.parse(text) as T;
} catch {
// Not valid JSON despite the content type: keep the payload as it was received.
return body as T;
}
}

/**
* Determine if the message is a CloudEvent
* @param {Message<T>} message an MQTTMessage
Expand Down
17 changes: 17 additions & 0 deletions test/integration/mqtt_tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,23 @@ describe("MQTT transport", () => {
expect(event).to.deep.equal(fixture);
});

it("Parses JSON data of a binary Message received as a Buffer or a string", () => {
const message = MQTT.binary(fixture);
for (const payload of [Buffer.from(JSON.stringify(data)), JSON.stringify(data)]) {
// An MQTT client receives the payload as bytes, not as the original object
const received = { ...message, body: payload, PUBLISH: message.PUBLISH } as unknown as Message<string>;
const event = MQTT.toEvent(received) as CloudEvent<Idata>;
expect(event.data).to.deep.equal(data);
}
});

it("Keeps text data of a binary Message that is not valid JSON", () => {
const message = MQTT.binary(fixture);
const received = { ...message, body: "not json", PUBLISH: message.PUBLISH } as unknown as Message<string>;
const event = MQTT.toEvent(received) as CloudEvent<string>;
expect(event.data).to.equal("not json");
});

it("A CloudEvent can be converted from a structured Message", () => {
const message = MQTT.structured(fixture);
const event = MQTT.toEvent(message);
Expand Down
Loading