diff --git a/handler.go b/handler.go index 96483a8..c9d0bbb 100644 --- a/handler.go +++ b/handler.go @@ -19,9 +19,9 @@ const ( ) type Handler struct { - Schema *graphql.Schema - - pretty bool + Schema *graphql.Schema + RootObject map[string]interface{} + pretty bool } type RequestOptions struct { Query string `json:"query" url:"query" schema:"query"` @@ -125,11 +125,11 @@ func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r * RequestString: opts.Query, VariableValues: opts.Variables, OperationName: opts.OperationName, + RootObject: h.RootObject, Context: ctx, } result := graphql.Do(params) - if h.pretty { w.WriteHeader(http.StatusOK) buff, _ := json.MarshalIndent(result, "", "\t") @@ -138,7 +138,7 @@ func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r * } else { w.WriteHeader(http.StatusOK) buff, _ := json.Marshal(result) - + w.Write(buff) } } @@ -149,14 +149,16 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } type Config struct { - Schema *graphql.Schema - Pretty bool + Schema *graphql.Schema + RootObject map[string]interface{} + Pretty bool } func NewConfig() *Config { return &Config{ - Schema: nil, - Pretty: true, + Schema: nil, + RootObject: map[string]interface{}{}, + Pretty: true, } } @@ -169,7 +171,8 @@ func New(p *Config) *Handler { } return &Handler{ - Schema: p.Schema, - pretty: p.Pretty, + Schema: p.Schema, + RootObject: p.RootObject, + pretty: p.Pretty, } } diff --git a/handler_test.go b/handler_test.go index 4c9fa0c..a51b777 100644 --- a/handler_test.go +++ b/handler_test.go @@ -151,3 +151,48 @@ func TestHandler_Params_NilParams(t *testing.T) { _ = handler.New(nil) } + +func TestHandler_Params_RootObject(t *testing.T) { + rootObject := map[string]interface{}{ + "foo": "bar", + } + + myNameQuery := graphql.NewObject(graphql.ObjectConfig{ + Name: "Query", + Fields: graphql.Fields{ + "name": &graphql.Field{ + Name: "name", + Type: graphql.String, + Resolve: func(p graphql.ResolveParams) (interface{}, error) { + return p.Info.RootValue.(map[string]interface{})["foo"], nil + }, + }, + }, + }) + myNameSchema, err := graphql.NewSchema(graphql.SchemaConfig{myNameQuery, nil}) + if err != nil { + t.Fatal(err) + } + + expected := &graphql.Result{ + Data: map[string]interface{}{ + "name": rootObject["foo"], + }, + } + queryString := `query={name}` + req, _ := http.NewRequest("GET", fmt.Sprintf("/graphql?%v", queryString), nil) + + h := handler.New(&handler.Config{ + Schema: &myNameSchema, + RootObject: rootObject, + Pretty: true, + }) + + result, resp := executeTest(t, h, req) + if resp.Code != http.StatusOK { + t.Fatalf("unexpected server response %v", resp.Code) + } + if !reflect.DeepEqual(result, expected) { + t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result)) + } +}