Skip to content

Commit

Permalink
Handle empty variables map correctly.
Browse files Browse the repository at this point in the history
Previously, only the nil variables map was handled correctly
by fully omitting the variables from the generated GraphQL query.
This change makes it so that an empty variables map is handled
equivalently, and adds test coverage for it.
  • Loading branch information
dmitshur committed Sep 8, 2018
1 parent 62c9ce0 commit 3658993
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
37 changes: 37 additions & 0 deletions graphql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package graphql_test
import (
"context"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
Expand Down Expand Up @@ -100,6 +101,34 @@ func TestClient_Query_noDataWithErrorResponse(t *testing.T) {
}
}

// Test that an empty (but non-nil) variables map is
// handled no differently than a nil variables map.
func TestClient_Query_emptyVariables(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/graphql", func(w http.ResponseWriter, req *http.Request) {
body := mustRead(req.Body)
if got, want := body, `{"query":"{user{name}}"}`+"\n"; got != want {
t.Errorf("got body: %v, want %v", got, want)
}
w.Header().Set("Content-Type", "application/json")
mustWrite(w, `{"data": {"user": {"name": "Gopher"}}}`)
})
client := graphql.NewClient("/graphql", &http.Client{Transport: localRoundTripper{handler: mux}})

var q struct {
User struct {
Name string
}
}
err := client.Query(context.Background(), &q, map[string]interface{}{})
if err != nil {
t.Fatal(err)
}
if got, want := q.User.Name, "Gopher"; got != want {
t.Errorf("got q.User.Name: %q, want: %q", got, want)
}
}

// localRoundTripper is an http.RoundTripper that executes HTTP transactions
// by using handler directly, instead of going over an HTTP connection.
type localRoundTripper struct {
Expand All @@ -112,6 +141,14 @@ func (l localRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)
return w.Result(), nil
}

func mustRead(r io.Reader) string {
b, err := ioutil.ReadAll(r)
if err != nil {
panic(err)
}
return string(b)
}

func mustWrite(w io.Writer, s string) {
_, err := io.WriteString(w, s)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ import (

func constructQuery(v interface{}, variables map[string]interface{}) string {
query := query(v)
if variables != nil {
if len(variables) > 0 {
return "query(" + queryArguments(variables) + ")" + query
}
return query
}

func constructMutation(v interface{}, variables map[string]interface{}) string {
query := query(v)
if variables != nil {
if len(variables) > 0 {
return "mutation(" + queryArguments(variables) + ")" + query
}
return "mutation" + query
Expand Down

0 comments on commit 3658993

Please sign in to comment.