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

Current implementation always uses POST as the transport mechanism. Adding GET support enables usage of GET queries for caching simply via URL.

Some notes:
- I left the existing API for creating a new client as is, but the implementation could be much cleaner by introducing some sort of configuration struct when creating a new client
- The construction of the query parameters follows the logic from Apollo's client implementation, which can be found here https://github.com/apollographql/apollo-client/blob/8beb4820edc6352996e08f7f73bde3573f1eb666/src/link/http/rewriteURIForGET.ts
- Updated integration tests to use both sets of clients. Updating the tests to use a test suite would be cleaner
This commit is contained in:
salman-rb
2022-04-13 16:16:27 -07:00
committed by GitHub
parent b2422452a1
commit 39a980ab4e
10 changed files with 798 additions and 335 deletions
+1
View File
@@ -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:
+28
View File
@@ -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:
```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: