Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for client that uses GET as transport mechanism #186

Merged
merged 2 commits into from
Apr 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ When releasing a new version:

- genqlient can now run as a portable binary (i.e. without a local checkout of the repository or `go run`).
- You can now enable `use_extensions` in the configuration file, to receive extensions returned by the GraphQL API server. Generated functions will return extensions as `map[string]interface{}`, if enabled.
- You can now use `graphql.NewClientUsingGet` to create a client that uses query parameters to pass the query to the GraphQL API server.

### Bug fixes:

Expand Down
28 changes: 28 additions & 0 deletions docs/FAQ.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,34 @@ This document describes common questions about genqlient, and provides an index

There's a [doc for that](INTRODUCTION.md)!

## … use GET requests instead of POST requests?

You can use `graphql.NewClientUsingGet` to create a client that will use query parameters to create the request. For example:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's probably worthwhile to give an example of what this sends over the wire to the server, since it's not obvious what the server would need to do to handle such a request -- unless there's a standard for how to do graphql over GET? I know there's a standard for POST but I don't know about GET. (If there is a standard for GET, it may be worth linking to it.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it's semi-standard. (The official spec has almost nothing about wire format, but the graphql-js and Apollo implementations are effectively the standard.) May as well include the link but in practice I think most servers will either support it or not.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Didn't link directly (not sure if this will be stable) but described the format in the FAQ

```go
ctx := context.Background()
client := graphql.NewClientUsingGet("https://api.github.com/graphql", http.DefaultClient)
resp, err := getUser(ctx, client, "benjaminjkraft")
fmt.Println(resp.User.Name, err)
```

This request will be sent via an HTTP GET request, with the query, operation name and variables encoded in the URL.

For example, if the query is defined as:

```graphql
query getUser($login: String!) {
user(login: $login) {
name
}
}
```

The URL requested will be:

`https://api.github.com/graphql?operationName%3DgetUser%26query%3D%0Aquery%20getUser(%24login%3A%20String!)%20%7B%0A%20%20user(login%3A%20%24login)%20%7B%0A%20%20%20%20name%0A%20%20%7D%0A%7D%0A%26variables%3D%7B%22login%22%3A%22benjaminjkraft%22%7D`

The client does not support mutations, and will return an error if passed a request that attempts one.

### … use an API that requires authentication?

When you call `graphql.NewClient`, pass in an HTTP client that adds whatever authentication headers you need (typically by wrapping the client's `Transport`). For example:
Expand Down
101 changes: 93 additions & 8 deletions graphql/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"

"github.com/vektah/gqlparser/v2/gqlerror"
)
Expand Down Expand Up @@ -53,10 +56,30 @@ type client struct {
// The typical method of adding authentication headers is to wrap the client's
// Transport to add those headers. See example/caller.go for an example.
func NewClient(endpoint string, httpClient Doer) Client {
return newClient(endpoint, httpClient, http.MethodPost)
}

// NewClientUsingGet returns a Client which makes requests to the given endpoint,
// suitable for most users.
//
// The client makes GET requests to the given GraphQL endpoint using a GET query,
// with the query, operation name and variables encoded as URL parameters.
// It will use the given http client, or http.DefaultClient if a nil client is passed.
//
// The client does not support mutations, and will return an error if passed a request
// that attempts one.
//
// The typical method of adding authentication headers is to wrap the client's
// Transport to add those headers. See example/caller.go for an example.
func NewClientUsingGet(endpoint string, httpClient Doer) Client {
return newClient(endpoint, httpClient, http.MethodGet)
}

func newClient(endpoint string, httpClient Doer, method string) Client {
if httpClient == nil || httpClient == (*http.Client)(nil) {
httpClient = http.DefaultClient
}
return &client{httpClient, endpoint, http.MethodPost}
return &client{httpClient, endpoint, method}
}

// Doer encapsulates the methods from *http.Client needed by Client.
Expand Down Expand Up @@ -100,15 +123,14 @@ type Response struct {
}

func (c *client) MakeRequest(ctx context.Context, req *Request, resp *Response) error {
body, err := json.Marshal(req)
if err != nil {
return err
var httpReq *http.Request
var err error
if c.method == http.MethodGet {
httpReq, err = c.createGetRequest(req)
} else {
httpReq, err = c.createPostRequest(req)
}

httpReq, err := http.NewRequest(
c.method,
c.endpoint,
bytes.NewReader(body))
if err != nil {
return err
}
Expand Down Expand Up @@ -142,3 +164,66 @@ func (c *client) MakeRequest(ctx context.Context, req *Request, resp *Response)
}
return nil
}

func (c *client) createPostRequest(req *Request) (*http.Request, error) {
body, err := json.Marshal(req)
if err != nil {
return nil, err
}

httpReq, err := http.NewRequest(
c.method,
c.endpoint,
bytes.NewReader(body))
if err != nil {
return nil, err
}

return httpReq, nil
}

func (c *client) createGetRequest(req *Request) (*http.Request, error) {
parsedURL, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}

queryParams := parsedURL.Query()
queryUpdated := false

if req.Query != "" {
if strings.HasPrefix(strings.TrimSpace(req.Query), "mutation") {
return nil, errors.New("client does not support mutations")
}
queryParams.Set("query", req.Query)
queryUpdated = true
}

if req.OpName != "" {
queryParams.Set("operationName", req.OpName)
queryUpdated = true
}

if req.Variables != nil {
variables, variablesErr := json.Marshal(req.Variables)
if variablesErr != nil {
return nil, variablesErr
}
queryParams.Set("variables", string(variables))
queryUpdated = true
}

if queryUpdated {
parsedURL.RawQuery = queryParams.Encode()
}

httpReq, err := http.NewRequest(
c.method,
parsedURL.String(),
http.NoBody)
if err != nil {
return nil, err
}

return httpReq, nil
}
68 changes: 68 additions & 0 deletions internal/integration/generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading