0

I have an object that is something like this:

{
  "colorRestrictions": {
    "availableColors":[ ... ], 
    "excludedColors": [ ... ]
  }
}

How do I translate this into a proto file considering that colorRestriction is an object that can have either of the arrays?

The property oneof doesn't allow for repeated within the declaration.

I guess it's something common but I couldn't find a straight answer, any suggestions? Thanks

Mido
  • 89
  • 1
  • 10
  • Do you really need to strictly have one or the other? Can you give one of them priority on the other if both are set? – Clément Jean May 03 '22 at 06:16
  • At least one of them needs to be set and there's no priority. – Mido May 03 '22 at 10:42
  • My point was more like: Could we have both set in any situation and then you chose which one you want to use programatically? – Clément Jean May 03 '22 at 11:26
  • This is part of an API where there is validation, it's already public and can't be modified. Currently allow for either one to be set, if none is set throw an error. – Mido May 03 '22 at 11:55

1 Answers1

1

Fields are all optional in Protobuf 3. So just define ordinary fields.

message ColorRestriction {
  repeated Color available_colors = 1;
  repeated Color excluded_colors = 2;
}

oneof is for mutually-exclusive fields. It doesn't require that a field is present; a oneof can be unset.

Even in Protobuf 2 repeated fields couldn't be marked as required. repeated fields don't have normal field presence because "empty list" is encoded identically to "unset list." When you need presence information in a repeated field (e.g., to include it in a oneof or distinguish "empty list" from "unset list") you can wrap it in a message.

message ColorRestriction {
  ColorList available_colors = 1;
  ColorList excluded_colors = 2;
}

message ColorList {
  repeated Color colors = 1;
}
Eric Anderson
  • 24,057
  • 5
  • 55
  • 76