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

Enumerations strange behavior in Node.js #8595

Closed
leaves4j opened this issue Nov 1, 2016 · 4 comments
Closed

Enumerations strange behavior in Node.js #8595

leaves4j opened this issue Nov 1, 2016 · 4 comments
Assignees
Milestone

Comments

@leaves4j
Copy link

leaves4j commented Nov 1, 2016

proto

syntax = "proto3";
package helloworld;
service Greeter {
    rpc SayHello (request) returns (request) {
    }
}
message request {
    TestEnum testEnum = 1;
}
enum TestEnum {
    UNKNOWN = 0;
    A = 1;
    B = 2;
}

server.js

...
function sayHello({request}, callback) {
  console.log(request.testEnum, request.testEnum == hello_proto.TestEnum.A);//'A'  false
  callback(null,  {testEnum: hello_proto.TestEnum.A})
}
...

client.js

...
console.log(hello_proto.TestEnum.A) // 1
client.sayHello({testEnum: hello_proto.TestEnum.A},(err,res) => {});
...

enum in server doesn't equal enum in client

@murgatroid99
Copy link
Member

OK, it looks like the root cause of this issue is #8726. They are evaluating unequal because they are being deserialized in a different format than they exist in the enum object. An option to change this behavior will be added in #9004.

@murgatroid99
Copy link
Member

The new package @grpc/proto-loader includes options for how enums are deserialized.

@charandas
Copy link

charandas commented Jul 20, 2018

For anyone that lands here, the new package @grpc/proto-loader worked for me. I do want to add that if you use enums beginning at 0, you would need:

const packageDefinition = protoLoader.loadSync('your_proto.proto', {
  enums: String,
  defaults: true, // needed this as well
.... code omitted
})

I am not sure if this is a bug because I am testing with grpcc and am explicitly passing in a 0 for the enum field, but it would simply get stripped (if not for defaults: true).

@murgatroid99
Copy link
Member

That is how it is supposed to work. The protobuf 3 language guide says

every enum definition must contain a constant that maps to zero as its first element. This is because:

  • There must be a zero value, so that we can use 0 as a numeric default value.
  • The zero value needs to be the first element, for compatibility with the proto2 semantics where the first enum value is always the default.

Then, like with any other field type, default values are omitted unless you specify defaults: true.

@lock lock bot locked as resolved and limited conversation to collaborators Oct 21, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants