【问题标题】:Working with a message having repeated field处理具有重复字段的消息
【发布时间】:2018-07-19 18:34:51
【问题描述】:

我的 Proto 文件看起来像这样 -

message Todos {
  repeated Todo todos = 1;
}

message Todo {
  int32 id = 1;
  string name = 2;
  bool done = 3;
}

当我从服务器发送 {todos: [...]} 时它运行良好,但在直接发送数组时得到一个空对象 {}。

服务器

getAll(_, callback) {
   console.log(todos);
   return callback(null, { todos });
}

客户

 client.getAll({}, function (err, res) {
    if (err) {
      return console.log(err);
    }
    console.log('todos: ');
    return console.log(res);
 });

版本 -

  • @grpc/proto-loader - ^0.1.0
  • grpc - ^1.13.0

【问题讨论】:

  • 您是说如果您通过{todos} 而不是{todos: todos},您会得到不同的结果,还是这两种情况之间还有其他区别? todos 是空数组吗?如果是,您是否尝试过按照this GitHub issue 中的建议?
  • @murgatroid99 感谢您的建议,但我已经检查了我的服务器,并且 todos 是一个非空数组。当发送 { todos } 或 { todos : todos } 时,我的客户得到一个对象。但是当我发送 todos(作为直接数组)时,它会得到一个空对象。
  • 这可能是因为我如何定义原型吗?

标签: javascript node.js protocol-buffers grpc


【解决方案1】:

就我而言,我试图返回一个数组,但似乎你总是必须返回一个对象....

hero.proto

syntax = "proto3";

package hero;

service HeroService {
  rpc GetHeroById(HeroById) returns (Hero) {}
  rpc ListHeroesById(HeroById) returns (HeroList) {}
}

message HeroById {
  int32 id = 1;
}

message Hero {
  int32 id = 1;
  string name = 2;
}

message HeroList {
  repeated Hero heroes = 1;
}

hero.controller.ts

@GrpcMethod('HeroService')
listHeroesById(data: HeroById, metadata: any): object {
  const items = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Doe' },
    { id: 3, name: 'Billy' },
  ];
  // make sure you return an object, even if you want an array!
  return { heroes: items.filter(({ id }) => id === data.id) };
}

在此处查看我的示例 TypeScript 项目:

https://github.com/kmturley/angular-nest-grpc

【讨论】:

  • 这是重要的信息。只返回数组,它必须是return { heroes }; 谢谢@Kim
【解决方案2】:

如果我理解正确,如果您只发送数组todos,而不是包含该数组的对象,则会遇到问题。仅发送数组只是对 API 的无效使用。 Protobuf 服务总是发送 protobuf 消息,因此您必须传递一个实际的消息对象,而不是该对象的单个字段。

【讨论】:

  • 太棒了!我后来想通了。感谢@murgatroid99 的帮助。
【解决方案3】:

如果你使用grpc.load,那么你可以发回一个数组:

callback(null, todos);

如果你使用protoLoader.loadSyncgrpc.loadPackageDefinition,那么你需要发回:

callback(null, { todos: todos });

【讨论】:

    猜你喜欢
    • 2014-12-28
    • 2016-04-18
    • 2012-06-03
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    相关资源
    最近更新 更多