Skip to content

Commit 7120e93

Browse files
authoredSep 9, 2022
fix: generate valid js code for aliased enum values (#1801)
1 parent 48457c4 commit 7120e93

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed
 

‎src/converter.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,20 @@ var Enum = require("./enum"),
1818
* @ignore
1919
*/
2020
function genValuePartial_fromObject(gen, field, fieldIndex, prop) {
21+
var defaultAlreadyEmitted = false;
2122
/* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
2223
if (field.resolvedType) {
2324
if (field.resolvedType instanceof Enum) { gen
2425
("switch(d%s){", prop);
2526
for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {
2627
// enum unknown values passthrough
27-
if (values[keys[i]] === field.typeDefault) { gen
28+
if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen
2829
("default:")
2930
("if(typeof(d%s)===\"number\"){m%s=d%s;break}", prop, prop, prop);
3031
if (!field.repeated) gen // fallback to default value only for
3132
// arrays, to avoid leaving holes.
3233
("break"); // for non-repeated fields, just ignore
34+
defaultAlreadyEmitted = true;
3335
}
3436
gen
3537
("case%j:", keys[i])

‎tests/cli.js

+2
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ tape.test("pbjs generates static code", function(test) {
6565
value: 42,
6666
},
6767
regularField: "abc",
68+
enumField: 0,
6869
};
6970
var obj1 = OneofContainer.toObject(OneofContainer.fromObject(obj));
7071
test.deepEqual(obj, obj1, "fromObject and toObject work for plain object");
@@ -76,6 +77,7 @@ tape.test("pbjs generates static code", function(test) {
7677
instance.messageInOneof = new Message();
7778
instance.messageInOneof.value = 42;
7879
instance.regularField = "abc";
80+
instance.enumField = 0;
7981
var instance1 = OneofContainerDynamic.toObject(OneofContainerDynamic.fromObject(instance));
8082
test.deepEqual(instance, instance1, "fromObject and toObject work for instance of the static type");
8183

‎tests/data/cli/test.proto

+9
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,19 @@ message Message {
44
int32 value = 1;
55
}
66

7+
enum Enum {
8+
option allow_alias = true;
9+
10+
UNSPECIFIED = 0;
11+
DEFAULT = 0; // checking that an alias does not break things
12+
SOMETHING = 1;
13+
}
14+
715
message OneofContainer {
816
oneof some_oneof {
917
string string_in_oneof = 1;
1018
Message message_in_oneof = 2;
1119
}
1220
string regular_field = 3;
21+
Enum enum_field = 4;
1322
}

0 commit comments

Comments
 (0)
Please sign in to comment.