ts-proto
ts-proto copied to clipboard
Convert enum zero values to undefined when using string enum
Assume we have enum in proto:
enum Product {
PRODUCT_UNSPECIFIED = 0;
PRODUCT_A = 1;
PRODUCT_B = 2;
}
message Example {
Product product = 1; // allow undefined
}
And generate code with options stringEnums=true
and enumsAsLiterals=true
,
when product
field is unset, the deserializer will output field = 'PRODUCT_UNSPECIFIED'
,
in actual development, is not so handy and I need to convert it again to undefined
.
So is good idea to add an option which auto convert zero enum value to undefined
or I should't use stringEnums
?
If it's ok to add an option, I'm glad to make a PR 😄
Huh, I was going to say that, because of proto3's default values are not serialized:
https://developers.google.com/protocol-buffers/docs/proto3#default
That we can't really know if the client "did not set product
at all" or "they set product to unspecified".
But your ask is, for either one, you don't really care, you really want unspecified to "go away" and just become undefined...
So yeah, I get what you're saying. Maybe a new option like enumUnspecifiedAsUndefined=true
...
Wouldn't this new option work for both stringEnums=true
and false
?
TFTR!
I think the new option only available for stringEnums=true
,
because number enum have easy way to check the field is unset or unspecified, like msg.enum === 0
but string enum can't.
Actually my current workaround is use number enum then use toJSON like below:
for (const key of ['enumfield1', 'enumfield2']) {
if (data[key] === 0) {
delete data[key]
}
}
return Message.toJSON(data)
toJSON
/ fromJSON
may also changed.
Have any other problems or side effects?