Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add message type as object in ProtoBuf (gRPC) - Proto3 Syntax?

How to send message type as object in ProtoBuf - Proto3 Syntax?

I want to transfer object instead of string or number.

Example

{
  name: 'One',
  date: 'date',
  some: 'some',
...
...
}
syntax = "proto3";

package db;

service Proxy
{
    rpc myFunction(Request) returns (Response);
}

message Request
{
    string name = 1;
}

message Response
{
    object keyvalue = 1;
}

Here, I am getting error

throw Error("no such Type or Enum '" + path + "' in " + this);
        ^

Error: no such Type or Enum 'object' in Type

--

Workaround

I can convert it to string in server side, and then I can JSON.parse() at client.

But I want to know, if there any better way to do it.

like image 465
Aravin Avatar asked Dec 17 '22 16:12

Aravin


1 Answers

protocol-buffer does not support the object data type!

But you can emulate your data as hierarchically by using protocol buffer message type itself.

syntax = "proto3";

package db;

service Proxy
{
    rpc myFunction(Request) returns (Response);
}

message Request
{
    string name = 1;
}

message Response
{
    message obj {
         string key1 = 1;
         string key2 = 2
    }
    obj keyvalue = 1;   // Here you have created your own type obj.
}

In the above example, you can see that the Response message now has "keyvalue" field of type obj(which is a custom type you have just built).

Now you will pass Object in a callback from the server instead of primitive type.

callback(null, { keyvalue: { key1: "value1", key2: "value2" } });

Let's say if keys are unknown to you but key/value pair data type is same and known to you then, in this case, you can use map<type, type>

message Response
{
   map<string, string> keyvalue = 1;
}
callback(null, { keyvalue: { "key1": "value1", "key5": "value2" } });

References:-

  • https://developers.google.com/protocol-buffers/docs/proto3#other
  • https://developers.google.com/protocol-buffers/docs/proto#scalar
  • https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Struct
like image 170
Abhishek Singh Avatar answered Jan 04 '23 04:01

Abhishek Singh