protocolbuffers / protobuf-javascript

BSD 3-Clause "New" or "Revised" License
373 stars 67 forks source link

Support for enum reverse mapping #225

Open YKampani opened 2 days ago

YKampani commented 2 days ago

I am trying to use this library to generate javascript files from proto files that has enums. I see while decoding the message using the deserializeBinary method that comes as part of the compiled js file, the enums are not getting mapped back to their corresponding string values. Is this feature already supported? Then can you let me know how to achieve it? If not then is there some change that we can make to support it in a forked version of this repositiory?

dibenede commented 1 day ago

We don't support this usage in this library. It is, however, something people ask for from time to time.

As a workaround, you could write a small tool that works off the proto descriptor to generate code for the mapping:

https://protobuf.dev/reference/cpp/api-docs/google.protobuf.descriptor/#Descriptor

You'll want something roughly like this :

const Descriptor* desc = FooMessage::GetDescriptor();
const FieldDescriptor* field_desc = desc->FindFieldByName("enum_field_name");
const EnumDescriptor* enum_desc = field_desc->enum_type();

// Note: this is definition, not tag order per https://github.com/protocolbuffers/protobuf/blob/aded9b76c477bc317fa5d4127d911f3a89be3e8f/src/google/protobuf/descriptor.h#L1326
for (const i = 0; i < enum_desc->value_count(); i++) {
  const EnumValueDescriptor* value_desc = enum_desc->value(i);
  const std::string value_name = value_desc->name()
  const int value_number = value_desc->number();

...
}

You could make it more generic by pulling the generated DescriptorPool and looking up your protobuf files by path. The descriptor API is present in other languages, excluding JS, with some variations.