2

How does one get the options associated with a protocol buffer field?

Suppose I have a field with a custom option like:

syntax = "proto3";

package main;

import "google/protobuf/descriptor.proto";

extend google.protobuf.FieldOptions {
   bool required = 7000;
}

message Person {
  string name = 1 [(required) = true];
}

Generated the js files with protoc

protoc -I . *.proto --js_out=import_style=commonjs,binary:js

I have read on how to retrieve the option in other languages from here, but can seem to get any working in Javascript.

Any help would be greatly appreciated!

pariola
  • 923
  • 12
  • 27
  • take care your link point to proto2 docs, for proto3 you should use [extension](https://developers.google.com/protocol-buffers/docs/proto#extensions) – Matteo Dec 14 '20 at 07:42
  • @Matteo they both point to proto2 docs, also I think Extensions are different from Custom Options – pariola Dec 14 '20 at 09:18

1 Answers1

4

Unfortunately this is not supported.

Other languages embed a "descriptor" for the proto file in the generated code. The descriptor contains information about a message, its fields, and also the custom options, all in binary protobuf format. See descriptor.proto

The code to read the extension is generated. If you had a FieldDescriptor, you could read your FieldOption extension. But you don't have this descriptor in Javascript generated code.

There is a possible workaround: You can use protoc to dump a FileDescriptorSet for your .proto file (see --descriptor_set_out option). You can read this binary message using Javascript (proto.google.protobuf.FileDescriptorSet from google-protobuf), navigate to your message, to the field in question, and then read your extension data to get the custom option value.

Timo Stamm
  • 610
  • 4
  • 10
  • If Typescript is an option for you, have a look at protobuf-ts (I am the author). It exposes custom options as plain JSON. See https://github.com/timostamm/protobuf-ts/blob/master/MANUAL.md#custom-options – Timo Stamm Dec 19 '20 at 00:02