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

Queries in context #1

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
56 changes: 50 additions & 6 deletions relay/relay.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package relay

import (
"context"
"encoding/base64"
"encoding/json"
"errors"
Expand Down Expand Up @@ -47,18 +48,36 @@ type Handler struct {
Schema *graphql.Schema
}

type Params struct {
Query string `json:"query"`
OperationName string `json:"operationName"`
Variables map[string]interface{} `json:"variables"`
}

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var params struct {
Query string `json:"query"`
OperationName string `json:"operationName"`
Variables map[string]interface{} `json:"variables"`
}
var params Params
if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

response := h.Schema.Exec(r.Context(), params.Query, params.OperationName, params.Variables)
// set parameters to context
ctx := WithParams(r.Context(), params)

response := h.Schema.Exec(ctx, params.Query, params.OperationName, params.Variables)

// check additional queries from context
if queries, ok := GetQueries(ctx); ok {
for topic, params := range queries {
addResponse := h.Schema.Exec(r.Context(), params.Query, params.OperationName, params.Variables)
// TODO: don't ignore error
if response.Extensions == nil {
response.Extensions = make(map[string]interface{})
}
response.Extensions[topic] = addResponse.Data
}
}

responseJSON, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
Expand All @@ -68,3 +87,28 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write(responseJSON)
}

type ctxKey int

const (
paramsKey ctxKey = iota
queriesKey
)

func WithParams(ctx context.Context, params Params) context.Context {
return context.WithValue(ctx, paramsKey, params)
}

func GetParams(ctx context.Context) (Params, bool) {
v, ok := ctx.Value(paramsKey).(Params)
return v, ok
}

func WithQueries(ctx context.Context, queries map[string]Params) context.Context {
return context.WithValue(ctx, queriesKey, queries)
}

func GetQueries(ctx context.Context) (map[string]Params, bool) {
v, ok := ctx.Value(queriesKey).(map[string]Params)
return v, ok
}
13 changes: 9 additions & 4 deletions relay/relay_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,19 @@ import (
"github.com/lygo/graphql-go/relay"
)

var starwarsSchema = graphql.MustParseSchema(starwars.Schema, &starwars.Resolver{})

func TestServeHTTP(t *testing.T) {
starwarsSchema := graphql.MustParseSchema(starwars.Schema, &starwars.Resolver{})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/some/path/here", strings.NewReader(`{"query":"{ hero { name } }", "operationName":"", "variables": null}`))
h := relay.Handler{Schema: starwarsSchema}

h.ServeHTTP(w, r)
ctx := relay.WithQueries(r.Context(), map[string]relay.Params{
"addition": {
Query: `{ hero(episode: EMPIRE) { name } }`,
},
})

h.ServeHTTP(w, r.WithContext(ctx))

if w.Code != 200 {
t.Fatalf("Expected status code 200, got %d.", w.Code)
Expand All @@ -28,7 +33,7 @@ func TestServeHTTP(t *testing.T) {
t.Fatalf("Invalid content-type. Expected [application/json], but instead got [%s]", contentType)
}

expectedResponse := `{"data":{"hero":{"name":"R2-D2"}}}`
expectedResponse := `{"data":{"hero":{"name":"R2-D2"}},"extensions":{"addition":{"hero":{"name":"Luke Skywalker"}}}}`
actualResponse := w.Body.String()
if expectedResponse != actualResponse {
t.Fatalf("Invalid response. Expected [%s], but instead got [%s]", expectedResponse, actualResponse)
Expand Down