예제 #1
0
파일: plural_test.go 프로젝트: N0hbdy/relay
func TestPluralIdentifyingRootField_AllowsFetching(t *testing.T) {
	query := `{
      usernames(usernames:["dschafer", "leebyron", "schrockn"]) {
        username
        url
      }
    }`
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"usernames": []interface{}{
				map[string]interface{}{
					"username": "******",
					"url":      "www.facebook.com/dschafer",
				},
				map[string]interface{}{
					"username": "******",
					"url":      "www.facebook.com/leebyron",
				},
				map[string]interface{}{
					"username": "******",
					"url":      "www.facebook.com/schrockn",
				},
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        pluralTestSchema,
		RequestString: query,
	})
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
예제 #2
0
func TestQuery_ExecutionDoesNotAddErrorsFromFieldResolveFn(t *testing.T) {
	qError := errors.New("queryError")
	q := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"a": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return nil, qError
				},
			},
			"b": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return "ok", nil
				},
			},
		},
	})
	blogSchema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: q,
	})
	if err != nil {
		t.Fatalf("unexpected error, got: %v", err)
	}
	query := "{ b }"
	result := graphql.Do(graphql.Params{
		Schema:        blogSchema,
		RequestString: query,
	})
	if len(result.Errors) != 0 {
		t.Fatalf("wrong result, unexpected errors: %+v", result.Errors)
	}
}
예제 #3
0
func TestNodeInterfaceAndFields_AllowsRefetching_ReturnsNullForBadIDs(t *testing.T) {
	query := `{
        node(id: "5") {
          id
        }
      }`
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"node": nil,
		},
		Errors: []gqlerrors.FormattedError{
			{
				Message:   "Unknown node",
				Locations: []location.SourceLocation{},
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        nodeTestSchema,
		RequestString: query,
	})

	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
예제 #4
0
func TestObjectIdentification_TestFetching_CorrectlyRefetchesTheEmpire(t *testing.T) {
	query := `
        query EmpireRefetchQuery {
          node(id: "RmFjdGlvbjoy") {
            id
            ... on Faction {
              name
            }
          }
        }
      `
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"node": map[string]interface{}{
				"id":   "RmFjdGlvbjoy",
				"name": "Galactic Empire",
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        starwars.Schema,
		RequestString: query,
	})
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
예제 #5
0
func main() {
	// Schema
	fields := graphql.Fields{
		"hello": &graphql.Field{
			Type: graphql.String,
			Resolve: func(p graphql.ResolveParams) interface{} {
				return "world"
			},
		},
	}
	rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields}
	schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}
	schema, err := graphql.NewSchema(schemaConfig)
	if err != nil {
		log.Fatalf("failed to create new schema, error: %v", err)
	}

	// Query
	query := `
		{
			hello
		}
	`
	params := graphql.Params{Schema: schema, RequestString: query}
	r := graphql.Do(params)
	if len(r.Errors) > 0 {
		log.Fatalf("failed to execute graphql operation, errors: %+v", r.Errors)
	}
	rJSON, _ := json.Marshal(r)
	fmt.Printf("%s \n", rJSON) // {“data”:{“hello”:”world”}}
}
예제 #6
0
func TestObjectIdentification_TestFetching_CorrectlyFetchesTheIDAndTheNameOfTheRebels(t *testing.T) {
	query := `
        query RebelsQuery {
          rebels {
            id
            name
          }
        }
      `
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"rebels": map[string]interface{}{
				"id":   "RmFjdGlvbjox",
				"name": "Alliance to Restore the Republic",
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        starwars.Schema,
		RequestString: query,
	})
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
예제 #7
0
파일: plural_test.go 프로젝트: N0hbdy/relay
func TestPluralIdentifyingRootField_Configuration_ArgNames_WrongArgNameSpecified(t *testing.T) {

	t.Skipf("Pending `validator` implementation")
	query := `{
      usernames(usernamesMisspelled:["dschafer", "leebyron", "schrockn"]) {
        username
        url
      }
    }`
	expected := &graphql.Result{
		Data: nil,
		Errors: []gqlerrors.FormattedError{
			gqlerrors.FormattedError{
				Message: `Unknown argument "usernamesMisspelled" on field "usernames" of type "Query".`,
				Locations: []location.SourceLocation{
					location.SourceLocation{Line: 2, Column: 17},
				},
			},
			gqlerrors.FormattedError{
				Message: `Field "usernames" argument "usernames" of type "[String!]!" is required but not provided.`,
				Locations: []location.SourceLocation{
					location.SourceLocation{Line: 2, Column: 7},
				},
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        pluralTestSchema,
		RequestString: query,
	})
	pretty.Println(result)
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
예제 #8
0
파일: handler.go 프로젝트: rs/rest-layer
// ServeHTTPC handles requests as a xhandler.HandlerC
func (h *Handler) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	var query string
	switch r.Method {
	case "GET":
		query = r.URL.Query().Get("query")
	case "POST":
		b, _ := ioutil.ReadAll(r.Body)
		r.Body.Close()
		if r.Header.Get("Content-Type") == "application/json" {
			q := map[string]interface{}{}
			if err := json.Unmarshal(b, &q); err != nil {
				http.Error(w, fmt.Sprintf("Cannot unmarshal JSON: %v", err), http.StatusBadRequest)
			}
			query, _ = q["query"].(string)
		} else {
			query = string(b)
		}
	default:
		http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
		return
	}
	result := graphql.Do(graphql.Params{
		Context:       ctx,
		RequestString: query,
		Schema:        h.schema,
	})
	if resource.Logger != nil {
		if len(result.Errors) > 0 {
			resource.Logger(ctx, resource.LogLevelError, fmt.Sprintf("wrong result, unexpected errors: %v", result.Errors), nil)
		}
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(result)
}
예제 #9
0
파일: node_test.go 프로젝트: solher/relay
func TestNodeInterfaceAndFields_AllowsRefetching_GetsTheCorrectWidthForPhotos(t *testing.T) {
	query := `{
        node(id: "4") {
          id
          ... on Photo {
            width
          }
        }
      }`
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"node": map[string]interface{}{
				"id":    "4",
				"width": 400,
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        nodeTestSchema,
		RequestString: query,
	})
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
예제 #10
0
// Async mutation using channels
func TestMutation_WithClientMutationId_BehavesCorrectly_SupportsPromiseMutations(t *testing.T) {
	query := `
        mutation M {
          simplePromiseMutation(input: {clientMutationId: "abc"}) {
            result
            clientMutationId
          }
        }
      `
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"simplePromiseMutation": map[string]interface{}{
				"result":           1,
				"clientMutationId": "abc",
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        mutationTestSchema,
		RequestString: query,
	})
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
예제 #11
0
// ContextHandler provides an entrypoint into executing graphQL queries with a
// user-provided context.
func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	// get query
	opts := NewRequestOptions(r)

	// execute graphql query
	params := graphql.Params{
		Schema:         *h.Schema,
		RequestString:  opts.Query,
		VariableValues: opts.Variables,
		OperationName:  opts.OperationName,
		Context:        ctx,
	}
	result := graphql.Do(params)

	if h.pretty {
		w.WriteHeader(http.StatusOK)
		buff, _ := json.MarshalIndent(result, "", "\t")

		w.Write(buff)
	} else {
		w.WriteHeader(http.StatusOK)
		buff, _ := json.Marshal(result)

		w.Write(buff)
	}
}
예제 #12
0
파일: node_test.go 프로젝트: solher/relay
func TestNodeInterfaceAndFields_AllowsRefetching_GetsTheCorrectNameForUsers(t *testing.T) {
	query := `{
        node(id: "1") {
          id
          ... on User {
            name
          }
        }
      }`
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"node": map[string]interface{}{
				"id":   "1",
				"name": "John Doe",
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        nodeTestSchema,
		RequestString: query,
	})
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
예제 #13
0
func customHandler(schema *graphql.Schema) func(http.ResponseWriter, *http.Request) {
	return func(rw http.ResponseWriter, r *http.Request) {
		opts := handler.NewRequestOptions(r)

		rootValue := map[string]interface{}{
			"response": rw,
			"request":  r,
		}

		params := graphql.Params{
			Schema:         *schema,
			RequestString:  opts.Query,
			VariableValues: opts.Variables,
			OperationName:  opts.OperationName,
			RootObject:     rootValue,
		}

		result := graphql.Do(params)

		jsonStr, err := json.Marshal(result)

		if err != nil {
			panic(err)
		}

		rw.Header().Set("Content-Type", "application/json")

		rw.Header().Set("Access-Control-Allow-Credentials", "true")
		rw.Header().Set("Access-Control-Allow-Methods", "POST")
		rw.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
		rw.Header().Set("Access-Control-Allow-Origin", "http://localhost:8080")

		rw.Write(jsonStr)
	}
}
예제 #14
0
func TestMutateAndGetPayload_AddsErrors(t *testing.T) {
	query := `
        mutation M {
          simpleMutation(input: {clientMutationId: "abc"}) {
            result
            clientMutationId
          }
        }
      `
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"simpleMutation": interface{}(nil),
		},
		Errors: []gqlerrors.FormattedError{
			gqlerrors.FormattedError{
				Message:   NotFoundError.Error(),
				Locations: []location.SourceLocation{},
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        mutationTestSchemaError,
		RequestString: query,
	})
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
func main() {
	// Save JSON of full schema introspection for Babel Relay Plugin to use
	result := graphql.Do(graphql.Params{
		Schema:        data.Schema,
		RequestString: testutil.IntrospectionQuery,
	})
	if result.HasErrors() {
		log.Fatalf("ERROR introspecting schema: %v", result.Errors)
		return
	} else {
		b, err := json.MarshalIndent(result, "", "  ")
		if err != nil {
			log.Fatalf("ERROR: %v", err)
		}
		err = ioutil.WriteFile("../data/schema.json", b, os.ModePerm)
		if err != nil {
			log.Fatalf("ERROR: %v", err)
		}

	}
	// TODO: Save user readable type system shorthand of schema
	// pending implementation of printSchema
	/*
		fs.writeFileSync(
		  path.join(__dirname, '../data/schema.graphql'),
		  printSchema(Schema)
		);
	*/
}
예제 #16
0
func TestGlobalIDFields_GivesDifferentIDs(t *testing.T) {
	query := `{
      allObjects {
        id
      }
    }`
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"allObjects": []interface{}{
				map[string]interface{}{
					"id": "VXNlcjox",
				},
				map[string]interface{}{
					"id": "VXNlcjoy",
				},
				map[string]interface{}{
					"id": "UGhvdG86MQ==",
				},
				map[string]interface{}{
					"id": "UGhvdG86Mg==",
				},
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        globalIDTestSchema,
		RequestString: query,
	})
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
예제 #17
0
func TestConnection_TestFetching_CorrectlyFetchesNoShipsOfTheRebelsAtTheEndOfTheConnection(t *testing.T) {
	query := `
        query RebelsQuery {
          rebels {
            name,
            ships(first: 3 after: "YXJyYXljb25uZWN0aW9uOjQ=") {
              edges {
                cursor,
                node {
                  name
                }
              }
            }
          }
        }
      `
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"rebels": map[string]interface{}{
				"name": "Alliance to Restore the Republic",
				"ships": map[string]interface{}{
					"edges": []interface{}{},
				},
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        starwars.Schema,
		RequestString: query,
	})
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
예제 #18
0
func TestGlobalIDFields_RefetchesTheIDs(t *testing.T) {
	query := `{
      user: node(id: "VXNlcjox") {
        id
        ... on User {
          name
        }
      },
      photo: node(id: "UGhvdG86MQ==") {
        id
        ... on Photo {
          width
        }
      }
    }`
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"user": map[string]interface{}{
				"id":   "VXNlcjox",
				"name": "John Doe",
			},
			"photo": map[string]interface{}{
				"id":    "UGhvdG86MQ==",
				"width": 300,
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        globalIDTestSchema,
		RequestString: query,
	})
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
예제 #19
0
func TestObjectIdentification_TestFetching_CorrectlyRefetchesTheXWing(t *testing.T) {
	query := `
        query XWingRefetchQuery {
          node(id: "U2hpcDox") {
            id
            ... on Ship {
              name
            }
          }
        }
      `
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"node": map[string]interface{}{
				"id":   "U2hpcDox",
				"name": "X-Wing",
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        starwars.Schema,
		RequestString: query,
	})
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
예제 #20
0
func TestExecutesResolveFunction_UsesProvidedResolveFunction(t *testing.T) {
	schema := testSchema(t, &graphql.Field{
		Type: graphql.String,
		Args: graphql.FieldConfigArgument{
			"aStr": &graphql.ArgumentConfig{Type: graphql.String},
			"aInt": &graphql.ArgumentConfig{Type: graphql.Int},
		},
		Resolve: func(p graphql.ResolveParams) (interface{}, error) {
			b, err := json.Marshal(p.Args)
			return string(b), err
		},
	})

	expected := map[string]interface{}{
		"test": "{}",
	}
	result := graphql.Do(graphql.Params{
		Schema:        schema,
		RequestString: `{ test }`,
	})
	if !reflect.DeepEqual(expected, result.Data) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result.Data))
	}

	expected = map[string]interface{}{
		"test": `{"aStr":"String!"}`,
	}
	result = graphql.Do(graphql.Params{
		Schema:        schema,
		RequestString: `{ test(aStr: "String!") }`,
	})
	if !reflect.DeepEqual(expected, result.Data) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result.Data))
	}

	expected = map[string]interface{}{
		"test": `{"aInt":-123,"aStr":"String!"}`,
	}
	result = graphql.Do(graphql.Params{
		Schema:        schema,
		RequestString: `{ test(aInt: -123, aStr: "String!") }`,
	})
	if !reflect.DeepEqual(expected, result.Data) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result.Data))
	}
}
예제 #21
0
func testGraphql(test T, p graphql.Params, t *testing.T) {
	result := graphql.Do(p)
	if len(result.Errors) > 0 {
		t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
	}
	if !reflect.DeepEqual(result, test.Expected) {
		t.Fatalf("wrong result, query: %v, graphql result diff: %v", test.Query, testutil.Diff(test.Expected, result))
	}
}
예제 #22
0
func TestMutation_ExecutionAddsErrorsFromFieldResolveFn(t *testing.T) {
	mError := errors.New("mutationError")
	q := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"a": &graphql.Field{
				Type: graphql.String,
			},
		},
	})
	m := graphql.NewObject(graphql.ObjectConfig{
		Name: "Mutation",
		Fields: graphql.Fields{
			"foo": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"f": &graphql.ArgumentConfig{
						Type: graphql.String,
					},
				},
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return nil, mError
				},
			},
			"bar": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"b": &graphql.ArgumentConfig{
						Type: graphql.String,
					},
				},
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return "ok", nil
				},
			},
		},
	})
	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query:    q,
		Mutation: m,
	})
	if err != nil {
		t.Fatalf("unexpected error, got: %v", err)
	}
	query := "mutation _ { newFoo: foo(f:\"title\") }"
	result := graphql.Do(graphql.Params{
		Schema:        schema,
		RequestString: query,
	})
	if len(result.Errors) == 0 {
		t.Fatal("wrong result, expected errors, got no errors")
	}
	if result.Errors[0].Error() != mError.Error() {
		t.Fatalf("wrong result, unexpected error, got: %v, expected: %v", result.Errors[0], mError)
	}
}
예제 #23
0
func executeQuery(query string, context *application.MyContext) *graphql.Result {
	result := graphql.Do(graphql.Params{
		Schema:        getUserSchema(context),
		RequestString: query,
	})
	if len(result.Errors) > 0 {
		fmt.Printf("wrong result, unexpected errors: %v", result.Errors)
	}
	return result
}
예제 #24
0
파일: main.go 프로젝트: cerisier/graphql
func executeQuery(query string, schema graphql.Schema) *graphql.Result {
	result := graphql.Do(graphql.Params{
		Schema:        schema,
		RequestString: query,
	})
	if len(result.Errors) > 0 {
		fmt.Printf("wrong result, unexpected errors: %v", result.Errors)
	}
	return result
}
예제 #25
0
func TestMutation_IntrospectsCorrectly_ContainsCorrectPayload(t *testing.T) {
	query := `{
        __type(name: "SimpleMutationPayload") {
          name
          kind
          fields {
            name
            type {
              name
              kind
              ofType {
                name
                kind
              }
            }
          }
        }
      }`
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"__type": map[string]interface{}{
				"name": "SimpleMutationPayload",
				"kind": "OBJECT",
				"fields": []interface{}{
					map[string]interface{}{
						"name": "result",
						"type": map[string]interface{}{
							"name":   "Int",
							"kind":   "SCALAR",
							"ofType": nil,
						},
					},
					map[string]interface{}{
						"name": "clientMutationId",
						"type": map[string]interface{}{
							"name": nil,
							"kind": "NON_NULL",
							"ofType": map[string]interface{}{
								"name": "String",
								"kind": "SCALAR",
							},
						},
					},
				},
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        mutationTestSchema,
		RequestString: query,
	})
	if !testutil.ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) {
		t.Fatalf("unexpected, result does not contain subset of expected data")
	}
}
예제 #26
0
func TestConnection_TestFetching_CorrectlyFetchesTheNextThreeShipsOfTheRebelsWithACursor(t *testing.T) {
	query := `
        query EndOfRebelShipsQuery {
          rebels {
            name,
            ships(first: 3 after: "YXJyYXljb25uZWN0aW9uOjE=") {
              edges {
                cursor,
                node {
                  name
                }
              }
            }
          }
        }
      `
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"rebels": map[string]interface{}{
				"name": "Alliance to Restore the Republic",
				"ships": map[string]interface{}{
					"edges": []interface{}{
						map[string]interface{}{
							"cursor": "YXJyYXljb25uZWN0aW9uOjI=",
							"node": map[string]interface{}{
								"name": "A-Wing",
							},
						},
						map[string]interface{}{
							"cursor": "YXJyYXljb25uZWN0aW9uOjM=",
							"node": map[string]interface{}{
								"name": "Millenium Falcon",
							},
						},
						map[string]interface{}{
							"cursor": "YXJyYXljb25uZWN0aW9uOjQ=",
							"node": map[string]interface{}{
								"name": "Home One",
							},
						},
					},
				},
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        starwars.Schema,
		RequestString: query,
	})
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}
예제 #27
0
파일: main.go 프로젝트: cerisier/graphql
func main() {
	http.HandleFunc("/graphql", func(w http.ResponseWriter, r *http.Request) {
		query := r.URL.Query()["query"][0]
		result := graphql.Do(graphql.Params{
			Schema:        testutil.StarWarsSchema,
			RequestString: query,
		})
		json.NewEncoder(w).Encode(result)
	})
	fmt.Println("Now server is running on port 8080")
	fmt.Println("Test with Get      : curl -g 'http://localhost:8080/graphql?query={hero{name}}'")
	http.ListenAndServe(":8080", nil)
}
예제 #28
0
func ExecuteQuery(query string, user repository.User) *graphql.Result {
	result := graphql.Do(graphql.Params{
		Schema:        schema,
		RequestString: query,
		Context:       context.WithValue(context.Background(), "currentUser", user),
	})
	if len(result.Errors) > 0 {
		fmt.Printf("Request payload:\n%s\n", query)
		fmt.Printf("Errors:\n")
		for i := 0; i < len(result.Errors); i++ {
			fmt.Printf("* %s\n", result.Errors[i].Error())
		}
	}
	return result
}
예제 #29
0
파일: main.go 프로젝트: cerisier/graphql
func graphqlHandler(w http.ResponseWriter, r *http.Request) {
	user := struct {
		ID   int    `json:"id"`
		Name string `json:"name"`
	}{1, "cool user"}
	result := graphql.Do(graphql.Params{
		Schema:        Schema,
		RequestString: r.URL.Query()["query"][0],
		Context:       context.WithValue(context.Background(), "currentUser", user),
	})
	if len(result.Errors) > 0 {
		log.Printf("wrong result, unexpected errors: %v", result.Errors)
		return
	}
	json.NewEncoder(w).Encode(result)
}
예제 #30
0
func TestMutation_IntrospectsCorrectly_ContainsCorrectInput(t *testing.T) {
	query := `{
        __type(name: "SimpleMutationInput") {
          name
          kind
          inputFields {
            name
            type {
              name
              kind
              ofType {
                name
                kind
              }
            }
          }
        }
      }`
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"__type": map[string]interface{}{
				"name": "SimpleMutationInput",
				"kind": "INPUT_OBJECT",
				"inputFields": []interface{}{
					map[string]interface{}{
						"name": "clientMutationId",
						"type": map[string]interface{}{
							"name": nil,
							"kind": "NON_NULL",
							"ofType": map[string]interface{}{
								"name": "String",
								"kind": "SCALAR",
							},
						},
					},
				},
			},
		},
	}
	result := graphql.Do(graphql.Params{
		Schema:        mutationTestSchema,
		RequestString: query,
	})
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
	}
}