Search code examples
javascripttypescriptprotocol-buffersprotoprotoc

assign values to repeated fields protobufs typescript


I have a protobuf message in service.proto

message DataUpdate {
  uint32 source = 1;
  uint32 destination = 2;
}

message DataUpdateRequest
{
  string filepath = 1;
  repeated DataUpdate updates = 2;
}

and I used protoc to get the js file for the above protobuf file and I assigned the values as follows in typescript file

function exec() {
  const servicePb = require('service_pb');
  const req = new servicePb.DataUpdateRequest();
  req.setFilepath('C:/Users/santhosh/test.txt');
  req.setUpdatesList([{
    source: 1,
    destination: 2,
  }]); // <- this line is throwing an error
  // sending req.serializeBinary() as data to endpoint
}

The error on setUpdatesList is:

TypeError: c[e].toArray is not a function
    at Function.push.../../node_modules/google-protobuf/google-protobuf.js.jspb.Message.setRepeatedWrapperField (google-protobuf.js:511:1)

How should I assign value to this type of message?

I tried from postman with the following json body (and Content-Type: application/json) and it worked

{
    "filepath": "C:/Users/santhosh/test.txt",
    "updates": [
        {
            "destination": 2,
            "source": 1
        }
    ]
}

How should I assign value to repeated field updatesList in typescript?


Solution

  • I figured out the solution. We need to use the setter of DataUpdate itself. So something like following would work.

    function exec() {
      const servicePb = require('service_pb');
      const req = new servicePb.DataUpdateRequest();
      req.setFilepath('C:/Users/santhosh/test.txt');
    
      // here is the change we need to make
      const dataUpdate = new servicePb.DataUpdate();
      dataUpdate.setSource(1);
      dataUpdate.setDestination(2);
      req.setUpdatesList([dataUpdate]); // or req.addUpdates(dataUpdate) will also work
    
      // sending req.serializeBinary() as data to endpoint
    }