0

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?

santhosh
  • 36
  • 8
  • this is an old reference talking about setWrapperField but not setRepeatedWrapperField https://github.com/protocolbuffers/protobuf/issues/5162 Attaching here just if it helps to understand the issue. – santhosh May 31 '22 at 10:49

1 Answers1

0

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
}
santhosh
  • 36
  • 8