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!
Advertisement
Answer
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.