How to read value of custom options from protobuf.js generated code?

794 views Asked by At

Similar to the example at: https://developers.google.com/protocol-buffers/docs/proto#extensions

Suppose I have a proto like:

import "google/protobuf/descriptor.proto";

extend google.protobuf.FieldOptions {
   string search_key = 7000;
}

message Person {
  string name = 1 [(search_key) = "searchIndex.firstName"];
}

then I use the protobufjs-cli to generate a static module:

pbjs -t static-module -w commonjs -o compiled.js test.proto

How can I then read the descriptor in javascript using the generated module?

1

There are 1 answers

0
UnknownBeef On BEST ANSWER

As mentioned in a comment, this required access to either the original .proto file or the output of:

pbjs -t proto3 -o compiled.proto myfile.proto

but once I had that it was simply a matter of:

import * as protobuf from 'protobufjs';

const root = protobuf.loadSync('test.proto')
const Person = root.lookupType('main.Person')
console.log(Person.fields.name.options!['(search_key)'])
// logs: searchIndex.firstName