How to use the keys of a message to set the type of other message property (Proto)

Viewed 33

I am trying to use the message keys to specify the property type in another message. Is there a way to do it in Proto or I need to create a oneOf and repeat the keys ?

message MessageName {
  string name = 1;
  string id = 2;
}

message AnotherMessage {
  [name|id] orderBy = 1; //here is where I need to use it as a type.
}
1 Answers

I think I understand the behaviour you are trying to obtain, however I am pretty sure you would gain in flexibility by using enums here. Indeed, you could create an OrderBy enumeration as the following:

enum OrderBy {
  // Unspecified OrderBy behaviour, you should default to whatever you want.
  ORDER_BY_UNSPECIFIED = 0;
  
  // Order by name.
  NAME = 1;

  // Order by ID.
  ID = 2;
}

message AnotherMessage {
  OrderBy orderBy = 1;
}

Your server implementation would then be responsible for understanding the orderBy field and responding accordingly.


Another possibility, which I do recommend and follow, would be to adopt the "Sorting Order" design pattern described by Google in its guide to designing APIs.

Related