hasura / go-graphql-client

Package graphql provides a GraphQL client implementation.
MIT License
405 stars 94 forks source link

feat: introduce dynamic GraphQL Builder #86

Open hgiasac opened 1 year ago

hgiasac commented 1 year ago

Introduce the Builder structure that wraps the naive [][2]interface{} type. It helps construct multiple queries to a request that needs to be conditionally added.

You might need to dynamically multiple queries or mutations in a single request. It isn't convenient with static structures. Builder helps us construct many queries flexibly.

For example, to make the following GraphQL mutation:

query($userId: String!, $disabled: Boolean!, $limit: Int!) {
    userByPk(userId: $userId) { id name }
    groups(disabled: $disabled) { id user_permissions }
    topUsers: users(limit: $limit) { id name }
}

# variables {
#   "userId": "1",
#   "disabled": false,
#   "limit": 5
# }

You can define:

type User struct {
    ID string
    Name string
}

var groups []struct {
    ID string
    Permissions []string `graphql:"user_permissions"`
}

var userByPk User
var topUsers []User

builder := graphql.NewBuilder().
    Query("userByPk(userId: $userId)", &userByPk).
    Query("groups(disabled: $disabled)", &groups).
    Query("topUsers: users(limit: $limit)", &topUsers).
    Variables(map[string]interface{}{
        "userId": 1,
        "disabled": false,
        "limit": 5,
    })

query, variables, err := builder.Build()
if err != nil {
    return err
}

err = client.Query(context.Background(), query, variables)
if err != nil {
    return err
}

// or use Query / Mutate shortcut methods
err = builder.Query(client)
if err != nil {
    return err
}
github-actions[bot] commented 1 year ago

Code Coverage

Package Line Rate Health
github.com/hasura/go-graphql-client 68%
github.com/hasura/go-graphql-client/ident 100%
github.com/hasura/go-graphql-client/pkg/jsonutil 86%
Summary 73% (1539 / 2114)

Minimum allowed line rate is 60%