Protobuf.js: Why doesnt fromObject() fail for invalid enum values?

Created on 10 May 2017  路  3Comments  路  Source: protobufjs/protobuf.js

protobuf.js version: 6.7.3

If I use MyMessage.fromObject({'myEnum': 'invalid'}) I would expect the function to fail in case invalid is not one of the possible options for the enum. Current behavior just ignores the field and doesn't add anything into the resulting MyMessage instance.

enum MyEnum {
  VAL1 = 0;
  VAL2 = 1;
}

message MyMessage {
  string id = 1;
  MyEnum myEnum = 2;
}

MyMessage.fromObject({'myEnum': 'invalid', id: "22"}) // returns {id: "22"} which is valid
enhancement

Most helpful comment

It would be nice then to have the verify function to support string values for enums as well then, or perhaps some other function that will have that kind of functionality. Currently I have to perform that validation by myself and I think it could be a useful addition to the library.

All 3 comments

fromObjectisn't a validator but does just one thing: Create a message from an object through naive conversions. It's not in the resulting message because MyEnum["invalid"] evaluates to undefined.

You can read more about this here: https://github.com/dcodeIO/protobuf.js#toolset

It would be nice then to have the verify function to support string values for enums as well then, or perhaps some other function that will have that kind of functionality. Currently I have to perform that validation by myself and I think it could be a useful addition to the library.

Hmm, well, when I think of it more, fromObject could also just throw in this case because it already throws for other "bogus" values. You're probably doing something like the following atm, correct?

function checkEnum(ReflectedEnum, val) {
  if (ReflectedEnum[val] == null)
    throw Error("not a valid enum value");
  return val;
}

MyMessage.fromObject({'myEnum': checkEnum(MyEnum, val), id: "22"})
Was this page helpful?
0 / 5 - 0 ratings

Related issues

andiwonder picture andiwonder  路  3Comments

thedillonb picture thedillonb  路  4Comments

mj-mehdizadeh picture mj-mehdizadeh  路  5Comments

filipednb picture filipednb  路  5Comments

jarvanxing picture jarvanxing  路  4Comments