Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with a message having repeated field

My Proto file looks like this -

message Todos {
  repeated Todo todos = 1;
}

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

It comes works fine when I send {todos: [...]} from the server, but gets an empty object {} when directly sending an array.

Server

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

Client

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

Versions -

  • @grpc/proto-loader - ^0.1.0
  • grpc - ^1.13.0
like image 619
Shobhit Chittora Avatar asked Feb 16 '26 05:02

Shobhit Chittora


1 Answers

In my case I was trying to return an array and it seems you always have to return an object....

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) };
}

Check out my example TypeScript project here:

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

like image 150
Kim T Avatar answered Feb 18 '26 20:02

Kim T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!