0

Loading .proto files can be done by providing file path (PROTO_PATH)

var packageDefinition = protoLoader.loadSync(
    PROTO_PATH,
    {keepCase: true,
     longs: String,
     enums: String,
     defaults: true,
     oneofs: true
    });

How to do this dynamically in node.js ? I want to construct proto schema (datatypes and functions) at run time.

npr
  • 4,325
  • 4
  • 20
  • 30
  • 1
    What do you mean by "do this dynamically"? Are you asking how to make that particular line of code more dynamic in some way, or are you looking to do something similar to what that line does, or something else? – murgatroid99 Nov 05 '18 at 22:39
  • Instead of providing .proto file as input, I want to construct .proto via grpc APIs. Is that possible ? – npr Nov 06 '18 at 08:23
  • @murgatroid99: is that possible ? – npr Nov 06 '18 at 16:33

1 Answers1

0

The @grpc/proto-loader library is specifically made to load .proto files, and does not support constructing protobuf message or service types dynamically at runtime.

However, Protobuf.js does support constructing protobuf reflection types at runtime (see its README for details), and it is possible to use that to construct a PackageDefinition object explicitly using that, and then load that into the grpc library. The type definitions in this document might be clearer.

murgatroid99
  • 19,007
  • 10
  • 60
  • 95
  • Thank you very much for clearing the doubt. Yes, protobufjs can be helpful - but I can NOT find a simple client-server example in it :( which uses json proto. I've raised an issue https://github.com/dcodeIO/protobuf.js/issues/1132 but no answers to it yet. Can you please point to any example code since you appear to be writing lot of gRPC ? – npr Nov 06 '18 at 20:56
  • I'm not exactly sure what you're asking, but I want to be clear that I am not suggesting that you create clients or servers using protobuf.js. Rather, I am suggesting that you use protobuf.js to assemble the type information you want, and then transform that into a data type that can be loaded into gRPC. I would suggest looking at the code of [the proto-loader library itself](https://github.com/grpc/grpc-node/tree/master/packages/proto-loader) for an example of how to do the second part. – murgatroid99 Nov 07 '18 at 00:53
  • I am currently doing this 1. Read a json file. 2. Convert it to .proto file (by string concat!) 3. Run server and client using this proto file. I want to get rid of step 2 which creates a .proto file. I want to create a proto file in memory or if there is a utility which can understand json equivalent of that proto file (like protobuf) would be fanastic. So that all three steps can be run seamlessly in one go. Protobuf does work with json file - however there is no example of simple client-and-server :( for it Hoping my query making sense. – npr Nov 07 '18 at 18:35