Skip to content

Commit

Permalink
fix: fromObject should not initialize oneof members
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-fenster committed Apr 28, 2021
1 parent 343e127 commit 893b164
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
8 changes: 3 additions & 5 deletions cli/targets/static.js
Original file line number Diff line number Diff line change
Expand Up @@ -394,8 +394,7 @@ function buildType(ref, type) {
if (config.comments) {
push("");
var jsType = toJsType(field);
if (field.optional && !field.map && !field.repeated && field.resolvedType instanceof Type ||
field.options && field.options.proto3_optional)
if (field.optional && !field.map && !field.repeated && field.resolvedType instanceof Type || field.partOf)
jsType = jsType + "|null|undefined";
pushComment([
field.comment || type.name + " " + field.name + ".",
Expand All @@ -411,9 +410,8 @@ function buildType(ref, type) {
push(escapeName(type.name) + ".prototype" + prop + " = $util.emptyArray;"); // overwritten in constructor
else if (field.map)
push(escapeName(type.name) + ".prototype" + prop + " = $util.emptyObject;"); // overwritten in constructor
else if (field.options && field.options.proto3_optional) {
push(escapeName(type.name) + ".prototype" + prop + " = null;"); // do not set default value for proto3 optional fields
}
else if (field.partOf)
push(escapeName(type.name) + ".prototype" + prop + " = null;"); // do not set default value for oneof members
else if (field.long)
push(escapeName(type.name) + ".prototype" + prop + " = $util.Long ? $util.Long.fromBits("
+ JSON.stringify(field.typeDefault.low) + ","
Expand Down
8 changes: 6 additions & 2 deletions tests/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ var Module = require("module");
var protobuf = require("..");

tape.test("pbjs generates static code", function(test) {
// pbjs does not seem to work with Node v4, so skip this test if we're running on it
if (process.versions.node.match(/^4\./)) {
test.end();
return;
}

// Alter the require cache to make the cli/targets/static work since it requires "protobufjs"
// and we don't want to mess with "npm link"
var savedResolveFilename = Module._resolveFilename;
Expand Down Expand Up @@ -59,8 +65,6 @@ tape.test("pbjs generates static code", function(test) {
instance.messageInOneof.value = 42;
instance.regularField = "abc";
var instance1 = OneofContainerDynamic.toObject(OneofContainerDynamic.fromObject(instance));
console.log(instance1);
// The following test fails: will be fixed by the next commit
test.deepEqual(instance, instance1, "fromObject and toObject work for instance of the static type");

test.end();
Expand Down

0 comments on commit 893b164

Please sign in to comment.