eclipse / paho.mqtt.javascript

paho.mqtt.javascript
Other
1.15k stars 467 forks source link

publish/(send!) is too awkward to use, requiring Message object creation #22

Closed jpwsutton closed 8 years ago

jpwsutton commented 8 years ago

migrated from Bugzilla #440770 status RESOLVED severity normal in component MQTT-JS for 1.1 Reported in version 1.0 on platform All Assigned to: Tang Zi Han

On 2014-07-30 09:07:00 -0400, Karl Palsson wrote:

The "Message" object is quite useful in the received case, containing information about length, topic, dup flag, and helpers to get the payload in multiple formats.

For publishing however, it's an obstacle.

To send a message, you are required to make the following calls..

var m = new Paho.MQTT.Message("some payload"); m.destinationName = "bulky/code/is/better/right"; m.qos = 2; m.retain = true; mqclient.send(m);

There's no reason for this at publish time. The only options available at publish time are qos, retain flag, topic and payload. If we can't simply have a publish method that accepts all these parameters. (with only topic and payload being required) can we at least have a better constructor?

either mqclient.send(topic, payload, qos=0, retain=false) or mqclient.send(new Paho.MQTT.Message("topic", "payload"))

I presume the second form wouldn't work, as the existing constructor puts the payload first, but really, anything would be an improvement. If we can't put hardcoded defaults on qos and retain flag, they could be client creation time options, if necessary.

On 2014-08-11 01:46:22 -0400, Tang Zi Han wrote:

It's better to add a new API, such as mqclient.publish(topic, publishOptions) publishOptions = { payload: "TEST", qos : 0, retain: false }

In this way , it also solve the below problem.

https://bugs.eclipse.org/bugs/show_bug.cgi?id=440771

On 2014-08-31 22:27:44 -0400, Tang Zi Han wrote:

Fixed by extending the send api to support parameters of topic,payload,qos,retained and keep backward compatiblity. Merged in develop branch.

this.send = function (topic,payload,qos,retained) {
var message ;

      if(arguments.length == 0){
          throw new Error("Invalid argument."+"length");

      }else if(arguments.length == 1) {

          if (!(topic instanceof Message) && (typeof topic !== "string"))
              throw new Error("Invalid argument:"+ typeof topic);

          message = topic;
          if (typeof message.destinationName === "undefined")
              throw new Error(format(ERROR.INVALID_ARGUMENT,[message.destinationName,"Message.destinationName"]));
          client.send(message); 

      }else {
          //parameter checking in Message object 
          message = new Message(payload);
          message.destinationName = topic;
          if(arguments.length >= 3)
              message.qos = qos;
          if(arguments.length >= 4)
              message.retained = retained;
          client.send(message); 
      }
  };