Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get protobuf.js to output enum strings instead of integers

I'm using the latest protobuf.js with Node.js 4.4.5.

I currently struggle to get protobuf.js to output the string definitions of enums instead of integers. I tried several suggestions, but none of them worked:

  • https://github.com/dcodeIO/ProtoBuf.js/issues/97
  • https://github.com/dcodeIO/protobuf.js/issues/349

I guess it's because of API changes in protobuf.js for the first one. For the second one, I can use the suggested solution partially, but if the message is nested within other messages, the builder seems to fall back to using the integer values, although the string values have been explicitly set.

Ideally, I'd like to overwrite the function which is used for producing the enum values, but I have a hard time finding the correct one with the debugger. Or is there a better way to achieve this for deeply nested objects?

like image 394
Tobi Avatar asked Jun 07 '16 19:06

Tobi


1 Answers

The generated JS code from protoc has a map in one direction only e.g.

 proto.foo.Bar.Myenum = {
  HEY: 0,
  HO: 1
};

Rationale for this is here but you have to the reverse lookup in your own JS code. There are lots of easy solutions for this. I used the one at https://stackoverflow.com/a/59360329/449347 i.e.

Generic reverse mapper function ...

 export function getKey(map, val) {
  return Object.keys(map).find(key => map[key] === val);
}

UT ...

import { Bar } from "js/proto/bar_pb";

expect(getKey(proto.foo.Bar.Myenum, 0)).toEqual("HEY");
expect(getKey(proto.foo.Bar.Myenum, 1)).toEqual("HO");
expect(getKey(proto.foo.Bar.Myenum, 99)).toBeUndefined();
like image 194
k1eran Avatar answered Oct 06 '22 01:10

k1eran