Permalink
Browse files

Handle empty variables map correctly.

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 Jun 21, 2018
1 parent 62c9ce0 commit 365899397c9ad12805631fe4c9b2a64be9d74818
Showing with 39 additions and 2 deletions.
  1. +37 −0 graphql_test.go
  2. +2 −2 query.go
View
@@ -3,6 +3,7 @@ package graphql_test
import (
"context"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
@@ -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 {
@@ -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 {
View
@@ -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

0 comments on commit 3658993

Please sign in to comment.