After decoding the byte buffer into a proto, my enum values are being returned (correctly) as integers. I'd like to convert them into their name if possible.
For example, I have a sourceType enum:
enum SourceType {
TestSource = 0;
}
var foo = proto.decode(bytes);
// foo.sourceType => 0
What's the best way to convert this integer into the enum value of SourceType?
You can get the runtime enum, which is a plain object, just like you'd get message classes:
var SourceType = builder.build("SourceType");
// { TestSource: 0 }
Afterwards, you can use that to look up the enum name from a value manually, or simply use a reflection helper:
...
var sourceTypeName = ProtoBuf.Reflect.Enum.getName(SourceType, foo.sourceType);
// "TestSource"
Of course the runtime enum is also available within the global namespace:
message MyMessage {
enum SourceType {
TestSource = 0;
}
}
...
var root = builder.build();
var SourceType = root.MyMessage.SourceType;
...
@dcodeIO: I tried this, but for nested messages I see the effect that once I use the object defined as above, it falls back to the "integer behavior", even if I set the enum name manually.
I also asked a StackOverflow question.
I'm working with the mesos.proto which is rather large.
ProtoBuf.Builder.Message.toRaw() seems to work.
It calls cloneRaw() which "converts enum values to their respective names".
@terranmoccasin: You should find this works:
var foo = proto.decode(bytes);
// foo.sourceType => 0
foo = proto.decode(bytes).toRaw();
// foo.sourceType => "TestSource"
Closing this for now.
Feel free to send a pull request if this is still a requirement.
I was able to convert then using decode options as following:
var fooDecoded = proto.decode(bytes);
var foo = proto.toObject(fooDecoded, {
enums: String,
longs: String,
arrays: true,
objects: true
});
Complete example using Awesome.proto example
var am = root.lookup("awesomepackage.AwesomeMessage");
var amessage = { awesomeField: "AwesomeString", fields: ["one","two"] };
var decoded = am.decode(am.encode(amessage).finish());
am.toObject(decoded, {
enums: String,
longs: String,
arrays: true,
objects: true
});
Most helpful comment
I was able to convert then using decode options as following:
Complete example using Awesome.proto example