protobuf.js version: 6.8.8
Protobuf's with optional enumerations are getting transformed into JS code with prototypes that default their value.
enum Foo {
Bar = 1;
}
message Msg {
optional Foo stuff = 1;
}
Is getting transformed into JS code that specifically sets the prototype to a incorrect value in the absence of the correct wire value.
npx pbjs --force-long -t static-module -w commonjs -o stuff.js stuff.proto
The following is a snippet of the important area. The entire js file is attached.
/**
* Msg stuff.
* @member {Foo} stuff
* @memberof Msg
* @instance
*/
Msg.prototype.stuff = 1;
Actually, to clarify, all fields seem to end up having some default value attached to their prototype. Perhaps someone could clarify why this is necessary? To me, unless the field contains [default = XXX] or required then all prototype assignments for fields should be null.
The prototype holds the default value of each field, or the respective field type's default value if there is no default specified. The encoder takes advantage of that by not having to emit a typeof check or similar. This also corresponds to the specification stating that the value of an omitted optional integer field isn't undefined or null but 0.
@dcodeIO, you're right. I misinterpreted that specification hint. Closing this.
Hey guys ! We just had the same issue on our side.
To know if the field has been set you can use hasOwnProperty (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty).
As protobuf.js uses the javascript prototype, hasOwnProperty return true if the field has been set, false otherwise.
Most helpful comment
Hey guys ! We just had the same issue on our side.
To know if the field has been set you can use
hasOwnProperty(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty).As protobuf.js uses the javascript prototype,
hasOwnPropertyreturntrueif the field has been set,falseotherwise.