处理具有重复字段的消息
Working with a message having repeated field
我的 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
而不是包含该数组的对象,就会遇到问题。仅发送数组只是对 API 的无效使用。 Protobuf 服务始终发送 protobuf 消息,因此您必须传递一个实际的消息对象,而不是该对象的单个字段。
如果你使用 grpc.load
那么你可以发回一个数组:
callback(null, todos);
如果你使用protoLoader.loadSync
和grpc.loadPackageDefinition
,那么你需要发回:
callback(null, { todos: todos });
在我的例子中,我试图return一个数组,似乎你总是必须return一个对象...
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 项目:
我的 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
而不是包含该数组的对象,就会遇到问题。仅发送数组只是对 API 的无效使用。 Protobuf 服务始终发送 protobuf 消息,因此您必须传递一个实际的消息对象,而不是该对象的单个字段。
如果你使用 grpc.load
那么你可以发回一个数组:
callback(null, todos);
如果你使用protoLoader.loadSync
和grpc.loadPackageDefinition
,那么你需要发回:
callback(null, { todos: todos });
在我的例子中,我试图return一个数组,似乎你总是必须return一个对象...
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 项目: