Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Checking if a field with a default value has been set #200

Closed
deepakmerugu opened this issue Nov 11, 2014 · 3 comments
Closed

Checking if a field with a default value has been set #200

deepakmerugu opened this issue Nov 11, 2014 · 3 comments

Comments

@deepakmerugu
Copy link

I'm trying to figure out if an optional field has been set in a proto. Can you please explain how to check if a field has been set. Currently, I'm observing that if a field has a default value and is not set, then on decoding, the object contains the default value. How can we distinguish this from the case where the field was indeed set with the same value as the default?

Thanks!

@dcodeIO
Copy link
Member

dcodeIO commented Nov 11, 2014

Currently there is no way to determine if the values have been explicitly set with the default value. There is, however, the possibility to check if the value equals the default value:

var myMessage = MyMessage.decode(...);
if (myMessage.someField === myMessage.$type.getChild("someField").defaultValue) {
    ...
}

@seishun
Copy link
Contributor

seishun commented May 1, 2015

The official C++ and Java implementations provide has_* methods for this functionality. But JavaScript can do better than that. Here's an API that I think would be idiomatic for JavaScript:

Consider a Message object obj and a field "foo".

  • obj.foo evaluates to the value of "foo" if it's set, otherwise to the default value for "foo". If "foo" doesn't have an explicit default, then it evaluates to the type-specific default.
  • obj.hasOwnProperty("foo") is true if "foo" is set, otherwise false.
  • delete obj.foo clears "foo". Afterwards, obj.hasOwnProperty("foo") is false and obj.foo is the default value.

This API could be implemented by using inheritance. I can produce a proof-of-concept if anyone is interested.

@dcodeIO
Copy link
Member

dcodeIO commented Nov 28, 2016

Closing this for now.

protobuf.js 6.0.0

Feel free to send a pull request if this is still a requirement.

@dcodeIO dcodeIO closed this as completed Nov 28, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants