mqtt-packet
mqtt-packet copied to clipboard
Write to stream fails when "userProperties" is an empy object
While using protocol version 5, calling writeToStream with userProperties being empty object {} method fails with false as return value.
This is the packet being written:
{
cmd: "publish",
topic: "protocol-version-debug",
payload: "{\"pattern\":\"protocol-version-debug\",\"data\":\"{\\\"ok\\\":1724704578895}\"}",
qos: 0,
retain: true,
messageId: 0,
dup: false,
properties: {
userProperties: {
},
},
}
I traced the problem to getProperties method which returns false when userProperties is empty object {} because getLengthProperty for empty object returns 0 causing getProperties to return false:
https://github.com/mqttjs/mqtt-packet/blob/1f2cf7f98ae036fae97096299d6237ae442ff9d8/writeToStream.js#L1004
Setting userProperties to something like {'f': 'u'} removes the issue.
We are using ClientMqtt from @nestjs/microservices to emit data to a topic.
const {
MqttRecordBuilder,
ClientProxyFactory,
Transport
} = require('@nestjs/microservices');
const client = ClientProxyFactory.create({
transport: Transport.MQTT,
options: {
url: 'mqtt://0.0.0.0:1883',
protocolVersion: 5,
}
})
const record = new MqttRecordBuilder()
.setData(JSON.stringify({ ok: new Date().getTime() }))
.setRetain(true)
.build();
client.emit('protocol-version-debug', record);
It seems the ClientMqtt sets userProperties to empty object when no userProperties is provided:
https://github.com/nestjs/nest/blob/e4b07eb06b406183e708269e0439f442a1dadb1c/packages/microservices/client/client-mqtt.ts#L217
Thanks for reporting! Would you like to send a Pull Request to address this issue? Remember to add unit tests.