处理具有重复字段的消息

时间:2018-07-19 18:34:51

标签: javascript node.js protocol-buffers grpc

我的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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

如果使用grpc.load,则可以发送回一个数组:

callback(null, todos);

如果您使用protoLoader.loadSyncgrpc.loadPackageDefinition,则需要发回:

callback(null, { todos: todos });

答案 2 :(得分:0)

在我的情况下,我试图返回一个数组,看来您总是必须返回一个对象 ....

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) };
}
相关问题