1

I am currently passing some tutorials about creating a Graphql server with gqlgen and gorm (mysql server).

Here is my code

type Player struct {
    ID     string `json:"id"`
    Name   string `json:"name"`
    TeamID int    `json:"team_id"`
}

type Team struct {
    ID      string    `json:"id"`
    Nat3    string    `json:"nat3"`
    Players []*Player `json:"players"`
}

...

func (r *queryResolver) Teams(ctx context.Context) ([]*model.Team, error) {
    var teams []*model.Team
    r.DB.Preload("Players").Find(&teams)

    return teams, nil
}

So by requesting "teams with players" it's working fine. However I am wondering if there is a way to skip preloading of Players, when players is not request by graphql client, like this:

query{
    teams {
        id
        nat3
    }
}

Above I do not request players but the preloading is executed, which produces unnecessary load on mysql server.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
user1908375
  • 1,069
  • 1
  • 14
  • 33

1 Answers1

0

You need an additional resolver for players. This is a general concept of GraphQL, not specifically Go and gqlgen.

In gqlgen you can specify a resolver for a particular field in your gqlgen.yml file. You should have a models property there. If you don't have it already, you can add it.

# top-level property
models:
  # name of your Go type
  Team:
    # fields, don't change this
    fields:
      # name of the field for which you want a resolver
      players:
        resolver: true

Then regenerate your Go code with go run github.com/99designs/gqlgen, or just go generate, if you followed the gqlgen project setup.

This should now generate somewhere a resolver type for Team, like this:

func (r *resolver) Team() schema.TeamResolver {
    return &teamResolver{r}
}

type teamResolver struct {
    *resolver // this should be the gqlgen root resolver
}

and its Players resolver, like this:

func (r *teamResolver) Players(ctx context.Context, obj *model.Team) ([]*model.Player, error) {
    // fetch players here
}

Now if the client request does not include players, this resolver won't run.

blackgreen
  • 34,072
  • 23
  • 111
  • 129