mqttjs / mqtt-packet

Parse and generate MQTT packets like a breeze in JS
Other
206 stars 93 forks source link

Current Typescript definitions are difficult to use to read userProperties #102

Closed bkp7 closed 3 years ago

bkp7 commented 3 years ago

Using TypeScript, reading user properties requires something like this (MQTT client):

client.on('message', function(topic, message, packet) {
  const pckt: IPublishPacket = Object.assign(packet);
  if (pckt.properties && pckt.properties.userProperties) {
    const userProperties: {[index: string]: string} = Object.assign(pckt.properties.userProperties);
    console.log(userProperties['test']);
  }
});

It would be better if the userProperties were changed from being {object} to being {[index: string]: string}.

It would also be better if the on message callback (in MQTT) required an IPublishPacket rather than the more generic Packet.

Changing both these would allow type assignments to be removed and the TypeScript code could be changed to:

client.on('message', function(topic, message, packet) {
  if (packet.properties && packet.properties.userProperties) {
    console.log(packet.properties.userProperties['test']);
  }
});

Linked to mqttjs/MQTT.js#1248