From d9144dea611c9a1c0e01cc3e0e2491c6de5f9c97 Mon Sep 17 00:00:00 2001 From: Damien Elmes Date: Fri, 8 Jul 2022 10:13:48 +1000 Subject: [PATCH] fix: proto3 optional scalars should default to null in reflection API (#1693) https://github.com/protobufjs/protobuf.js/pull/1584 made proto3 optional scalars default to null when using static/static-module, but the old behaviour remained when using reflection (eg json-module). --- src/field.js | 3 +++ tests/comp_optional.js | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/src/field.js b/src/field.js index 05d89cae8..e0feb8b43 100644 --- a/src/field.js +++ b/src/field.js @@ -270,6 +270,9 @@ Field.prototype.resolve = function resolve() { this.typeDefault = null; else // instanceof Enum this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined + } else if (this.options && this.options.proto3_optional) { + // proto3 scalar value marked optional; should default to null + this.typeDefault = null; } // use explicitly set default value if present diff --git a/tests/comp_optional.js b/tests/comp_optional.js index fd12fa9a5..f0a5e50f6 100644 --- a/tests/comp_optional.js +++ b/tests/comp_optional.js @@ -22,5 +22,9 @@ tape.test("proto3 optional", function(test) { test.equal(Message.oneofs._optionalInt32.name, '_optionalInt32'); test.deepEqual(Message.oneofs._optionalInt32.oneof, ['optionalInt32']); + var m = Message.create({}); + test.strictEqual(m.regularInt32, 0); + test.strictEqual(m.optionalInt32, null); + test.end(); });