Skip to content

Commit

Permalink
docs: clarify usage of structs as variables (shurcooL#66)
Browse files Browse the repository at this point in the history
* docs: clarify usage of structs as variables
  • Loading branch information
JoshuaDietz authored Jan 16, 2023
1 parent 7943bd6 commit 0ea43e0
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,33 @@ if err != nil {
}
```
Variables get encoded as normal json. So if you supply a struct for a variable and want to rename fields, you can do this like that:
```Go
type Dimensions struct {
Width int `json:"ship_width"`,
Height int `json:"ship_height"`
}

var myDimensions = Dimensions{
Width : 10,
Height : 6,
}

var mutation struct {
CreateDimensions struct {
ID string `graphql:"id"`
} `graphql:"create_dimensions(ship_dimensions: $ship_dimensions)"`
}

variables := map[string]interface{}{
"ship_dimensions": myDimensions,
}

err := client.Mutate(context.TODO(), &mutation, variables)

```
which will set `ship_dimensions` to an object with the properties `ship_width` and `ship_height`.
### Custom scalar tag
Because the generator reflects recursively struct objects, it can't know if the struct is a custom scalar such as JSON. To avoid expansion of the field during query generation, let's add the tag `scalar:"true"` to the custom scalar. If the scalar implements the JSON decoder interface, it will be automatically decoded.
Expand Down

0 comments on commit 0ea43e0

Please sign in to comment.