4

我正在Protobuf.js为 Node 使用,似乎尚不支持Any来自 proto3 的字段类型。

该模块的作者建议手动定义Any如下。

syntax = "proto3";
package google.protobuf;
message Any {
  string type_url = 1;
  bytes value = 2;
}

但是,我不太清楚在那之后我应该做什么。我编写了一个成功使用解决方法的最小脚本:

我的服务.proto

syntax = "proto3";  

package myservice;

message Any {
  string type_url = 1;
  bytes value = 2;
}

message Request {
    string id = 1;
}

message SampleA {
    string fieldA = 1;
}

message SampleB {
    string fieldB = 1;
}

message Response {
    string id = 1;
    repeated Any samples = 2;
}

service MyService {
  rpc Get (Request) returns (Response);
}

示例.js

const ProtoBuf = require('protobufjs');
const builder = ProtoBuf.loadProtoFile('./myservice.proto');
const Any = builder.build('Any');
const SampleA = builder.build('SampleA');
const SampleB = builder.build('SampleB');
const Response = builder.build('Response');

const pack = (message, prefix) => {
  return new Any({
    type_url: path.join((prefix || ''), message.toString()),
    value: message.encode()
  });
};

const unpack = (message) => {
  const b = builder.build(message.type_url.split('.')[1]);
  return b.decode(message.value);
};

// Pack and create a response
const sampleA = new SampleA({fieldA: 'testa'});
const sampleB = new SampleA({fieldA: 'testa'});
const response = new Response({
  id: '1234',
  samples: [pack(sampleA), pack(sampleB)]
});


// Unpack
const samples = response.samples.map((sample) => {
    return unpack(sample);
});

这有效,我得到了我的预期。但是,我有几个问题:

  1. 有没有更好的方法来获取消息的全名来构造 type_url。我在我的代码中使用了 .toString() 但我查看了其他语言的实现,并且消息似乎有某种名称的吸气剂。

  2. 在对 Any 消息进行编码和解码时,我应该使用 .encode 和 .decode 还是有更好的方法?

4

0 回答 0