Skip to content

Commit

Permalink
fix: generate valid js code for aliased enum values (#1801)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-fenster committed Sep 9, 2022
1 parent 48457c4 commit 7120e93
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/converter.js
Expand Up @@ -18,18 +18,20 @@ var Enum = require("./enum"),
* @ignore
*/
function genValuePartial_fromObject(gen, field, fieldIndex, prop) {
var defaultAlreadyEmitted = false;
/* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
if (field.resolvedType) {
if (field.resolvedType instanceof Enum) { gen
("switch(d%s){", prop);
for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {
// enum unknown values passthrough
if (values[keys[i]] === field.typeDefault) { gen
if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen
("default:")
("if(typeof(d%s)===\"number\"){m%s=d%s;break}", prop, prop, prop);
if (!field.repeated) gen // fallback to default value only for
// arrays, to avoid leaving holes.
("break"); // for non-repeated fields, just ignore
defaultAlreadyEmitted = true;
}
gen
("case%j:", keys[i])
Expand Down
2 changes: 2 additions & 0 deletions tests/cli.js
Expand Up @@ -65,6 +65,7 @@ tape.test("pbjs generates static code", function(test) {
value: 42,
},
regularField: "abc",
enumField: 0,
};
var obj1 = OneofContainer.toObject(OneofContainer.fromObject(obj));
test.deepEqual(obj, obj1, "fromObject and toObject work for plain object");
Expand All @@ -76,6 +77,7 @@ tape.test("pbjs generates static code", function(test) {
instance.messageInOneof = new Message();
instance.messageInOneof.value = 42;
instance.regularField = "abc";
instance.enumField = 0;
var instance1 = OneofContainerDynamic.toObject(OneofContainerDynamic.fromObject(instance));
test.deepEqual(instance, instance1, "fromObject and toObject work for instance of the static type");

Expand Down
9 changes: 9 additions & 0 deletions tests/data/cli/test.proto
Expand Up @@ -4,10 +4,19 @@ message Message {
int32 value = 1;
}

enum Enum {
option allow_alias = true;

UNSPECIFIED = 0;
DEFAULT = 0; // checking that an alias does not break things
SOMETHING = 1;
}

message OneofContainer {
oneof some_oneof {
string string_in_oneof = 1;
Message message_in_oneof = 2;
}
string regular_field = 3;
Enum enum_field = 4;
}

0 comments on commit 7120e93

Please sign in to comment.