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

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


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();