Search code examples
gogrpc-go

How do I create associations in gRPC proto files?


I'm might be going about it the wrong way, but I want to define a relationship between two or more structs (messages).

Using StackOverflow as an example, let's say I had a LabelService for CRUD actions on labels. I also have a QuestionService where a Question can have Labels. Let's also assume I have a UserService and a User can also have labels attached

# label.proto
service LabelService {
    rpc CreateLabel() returns();
    ...etc
}
message Label {
   string text = 1;
}

But now I want to create my QuestionService and Question message. Do I associate the two files some how or is this level of association done in the go code?

# question.proto
service QuestionService {
    rpc CreateQuestion() returns();
    ...etc
}
message Question {
   string text = 1;
   repeat Label labels = 2 # <-- how to do this?
}

# user.proto
service UserService {
    rpc CreateQuestion() returns();
    ...etc
}
message User {
   string name = 1;
   repeat Label labels = 2 # <-- how to do this?
}

I think I'm confused because for REST APIs and using gorm.io for example, I would setup the associations in the structs and have gorm.io create the tables.


Solution

  • From the docs:

    import "myproject/other_protos.proto";
    

    so just simply add an import in your question.proto to your user.proto. It's no different than when importing other standard proto definitions like timestamp and duration:

    import "google/protobuf/timestamp.proto";
    import "google/protobuf/duration.proto";