3

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!

2
  • take care your link point to proto2 docs, for proto3 you should use extension Commented Dec 14, 2020 at 7:42
  • @Matteo they both point to proto2 docs, also I think Extensions are different from Custom Options Commented Dec 14, 2020 at 9:18

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 github.com/timostamm/protobuf-ts/blob/master/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.