Example #1
0
func init() {
	nodeTestUserType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "User",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type: types.NewGraphQLNonNull(types.GraphQLID),
			},
			"name": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
		Interfaces: []*types.GraphQLInterfaceType{nodeTestDef.NodeInterface},
	})
	nodeTestPhotoType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Photo",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type: types.NewGraphQLNonNull(types.GraphQLID),
			},
			"width": &types.GraphQLFieldConfig{
				Type: types.GraphQLInt,
			},
		},
		Interfaces: []*types.GraphQLInterfaceType{nodeTestDef.NodeInterface},
	})

	nodeTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: nodeTestQueryType,
	})
}
func init() {
	globalIDTestUserType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "User",
		Fields: types.GraphQLFieldConfigMap{
			"id": gqlrelay.GlobalIdField("User", nil),
			"name": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
		Interfaces: []*types.GraphQLInterfaceType{globalIDTestDef.NodeInterface},
	})
	photoIdFetcher := func(obj interface{}, info types.GraphQLResolveInfo) string {
		switch obj := obj.(type) {
		case *photo2:
			return fmt.Sprintf("%v", obj.PhotoId)
		}
		return ""
	}
	globalIDTestPhotoType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Photo",
		Fields: types.GraphQLFieldConfigMap{
			"id": gqlrelay.GlobalIdField("Photo", photoIdFetcher),
			"width": &types.GraphQLFieldConfig{
				Type: types.GraphQLInt,
			},
		},
		Interfaces: []*types.GraphQLInterfaceType{globalIDTestDef.NodeInterface},
	})

	globalIDTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: globalIDTestQueryType,
	})
}
func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichRedefinesABuiltInType(t *testing.T) {

	fakeString := types.NewGraphQLScalarType(types.GraphQLScalarTypeConfig{
		Name: "String",
		Serialize: func(value interface{}) interface{} {
			return nil
		},
	})
	queryType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Query",
		Fields: types.GraphQLFieldConfigMap{
			"normal": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
			"fake": &types.GraphQLFieldConfig{
				Type: fakeString,
			},
		},
	})
	_, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: queryType,
	})
	expectedError := `Schema must contain unique named types but contains multiple types named "String".`
	if err == nil || err.Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, err)
	}
}
func schemaWithInputFieldOfType(ttype types.GraphQLType) (types.GraphQLSchema, error) {

	badInputObject := types.NewGraphQLInputObjectType(types.InputObjectConfig{
		Name: "BadInputObject",
		Fields: types.InputObjectConfigFieldMap{
			"badField": &types.InputObjectFieldConfig{
				Type: ttype,
			},
		},
	})
	return types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Query",
			Fields: types.GraphQLFieldConfigMap{
				"f": &types.GraphQLFieldConfig{
					Type: types.GraphQLString,
					Args: types.GraphQLFieldConfigArgumentMap{
						"badArg": &types.GraphQLArgumentConfig{
							Type: badInputObject,
						},
					},
				},
			},
		}),
	})
}
func TestTypeSystem_SchemaMustHaveObjectRootTypes_RejectsASchemaWithoutAQueryType(t *testing.T) {
	_, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{})
	expectedError := "Schema query must be Object Type but got: nil."
	if err == nil || err.Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, err)
	}
}
func init() {
	postType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Post",
		Fields: types.GraphQLFieldConfigMap{
			// Define `id` field as a Relay GlobalID field.
			// It helps with translating your GraphQL object's id into a global id
			// For eg:
			// 		For a `Post` type, with an id of `1`, it's global id will be `UG9zdDox`
			//      which is a base64 encoded version of `Post:1` string
			// We will explore more in the next part of this series.
			"id": gqlrelay.GlobalIdField("Post", nil),
			"text": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})

	queryType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Query",
		Fields: types.GraphQLFieldConfigMap{
			"latestPost": &types.GraphQLFieldConfig{
				Type: postType,
				Resolve: func(p types.GQLFRParams) interface{} {
					return GetLatestPost()
				},
			},
		},
	})

	Schema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: queryType,
	})

}
func TestTypeSystem_DefinitionExample_DefinesAMutationScheme(t *testing.T) {
	blogSchema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query:    blogQuery,
		Mutation: blogMutation,
	})
	if err != nil {
		t.Fatalf("unexpected error, got: %v", err)
	}

	if blogSchema.GetMutationType() != blogMutation {
		t.Fatalf("expected blogSchema.GetMutationType() == blogMutation")
	}

	writeMutation, _ := blogMutation.GetFields()["writeArticle"]
	if writeMutation == nil {
		t.Fatalf("writeMutation is nil")
	}
	writeMutationType := writeMutation.Type
	if writeMutationType != blogArticle {
		t.Fatalf("writeMutationType expected to equal blogArticle, got: %v", writeMutationType)
	}
	if writeMutationType.GetName() != "Article" {
		t.Fatalf("writeMutationType.Name expected to equal `Article`, got: %v", writeMutationType.GetName())
	}
	if writeMutation.Name != "writeArticle" {
		t.Fatalf("writeMutation.Name expected to equal `writeArticle`, got: %v", writeMutation.Name)
	}
}
func TestIntrospection_IdentifiesDeprecatedFields(t *testing.T) {

	testType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "TestType",
		Fields: types.GraphQLFieldConfigMap{
			"nonDeprecated": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
			"deprecated": &types.GraphQLFieldConfig{
				Type:              types.GraphQLString,
				DeprecationReason: "Removed in 1.0",
			},
		},
	})
	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: testType,
	})
	if err != nil {
		t.Fatalf("Error creating GraphQLSchema: %v", err.Error())
	}
	query := `
      {
        __type(name: "TestType") {
          name
          fields(includeDeprecated: true) {
            name
            isDeprecated,
            deprecationReason
          }
        }
      }
    `
	expected := &types.GraphQLResult{
		Data: map[string]interface{}{
			"__type": map[string]interface{}{
				"name": "TestType",
				"fields": []interface{}{
					map[string]interface{}{
						"name":              "nonDeprecated",
						"isDeprecated":      false,
						"deprecationReason": nil,
					},
					map[string]interface{}{
						"name":              "deprecated",
						"isDeprecated":      true,
						"deprecationReason": "Removed in 1.0",
					},
				},
			},
		},
	}
	result := graphql(t, gql.GraphqlParams{
		Schema:        schema,
		RequestString: query,
	})
	if !testutil.ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
	}
}
func TestTypeSystem_SchemaMustHaveObjectRootTypes_AcceptsASchemaWhoseQueryTypeIsAnObjectType(t *testing.T) {
	_, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: someObjectType,
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}
Example #10
0
func TestCorrectlyThreadsArguments(t *testing.T) {

	query := `
      query Example {
        b(numArg: 123, stringArg: "foo")
      }
    `

	var resolvedArgs map[string]interface{}

	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Type",
			Fields: types.GraphQLFieldConfigMap{
				"b": &types.GraphQLFieldConfig{
					Args: types.GraphQLFieldConfigArgumentMap{
						"numArg": &types.GraphQLArgumentConfig{
							Type: types.GraphQLInt,
						},
						"stringArg": &types.GraphQLArgumentConfig{
							Type: types.GraphQLString,
						},
					},
					Type: types.GraphQLString,
					Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
						resolvedArgs = p.Args
						return resolvedArgs
					},
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

	// parse query
	ast := testutil.Parse(t, query)

	// execute
	ep := executor.ExecuteParams{
		Schema: schema,
		AST:    ast,
	}
	result := testutil.Execute(t, ep)
	if len(result.Errors) > 0 {
		t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
	}

	expectedNum := 123
	expectedString := "foo"
	if resolvedArgs["numArg"] != expectedNum {
		t.Fatalf("Expected args.numArg to equal `%v`, got `%v`", expectedNum, resolvedArgs["numArg"])
	}
	if resolvedArgs["stringArg"] != expectedString {
		t.Fatalf("Expected args.stringArg to equal `%v`, got `%v`", expectedNum, resolvedArgs["stringArg"])
	}
}
Example #11
0
func TestAvoidsRecursion(t *testing.T) {

	doc := `
      query Q {
        a
        ...Frag
        ...Frag
      }

      fragment Frag on Type {
        a,
        ...Frag
      }
    `
	data := map[string]interface{}{
		"a": "b",
	}

	expected := &types.GraphQLResult{
		Data: map[string]interface{}{
			"a": "b",
		},
	}

	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Type",
			Fields: types.GraphQLFieldConfigMap{
				"a": &types.GraphQLFieldConfig{
					Type: types.GraphQLString,
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

	// parse query
	ast := testutil.Parse(t, doc)

	// execute
	ep := executor.ExecuteParams{
		Schema:        schema,
		AST:           ast,
		Root:          data,
		OperationName: "Q",
	}
	result := testutil.Execute(t, ep)
	if len(result.Errors) > 0 {
		t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
	}
	if !reflect.DeepEqual(expected, result) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
	}

}
func schemaWithFieldType(ttype types.GraphQLOutputType) (types.GraphQLSchema, error) {
	return types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Query",
			Fields: types.GraphQLFieldConfigMap{
				"f": &types.GraphQLFieldConfig{
					Type: ttype,
				},
			},
		}),
	})
}
func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichHaveSameNamedObjectsImplementingAnInterface(t *testing.T) {

	anotherInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{
		Name: "AnotherInterface",
		ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType {
			return nil
		},
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	_ = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "BadObject",
		Interfaces: []*types.GraphQLInterfaceType{
			anotherInterface,
		},
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	_ = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "BadObject",
		Interfaces: []*types.GraphQLInterfaceType{
			anotherInterface,
		},
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	queryType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Query",
		Fields: types.GraphQLFieldConfigMap{
			"iface": &types.GraphQLFieldConfig{
				Type: anotherInterface,
			},
		},
	})
	_, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: queryType,
	})
	expectedError := `Schema must contain unique named types but contains multiple types named "BadObject".`
	if err == nil || err.Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, err)
	}
}
Example #14
0
func TestThreadsContextCorrectly(t *testing.T) {

	query := `
      query Example { a }
    `

	data := map[string]interface{}{
		"contextThing": "thing",
	}

	var resolvedContext map[string]interface{}

	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Type",
			Fields: types.GraphQLFieldConfigMap{
				"a": &types.GraphQLFieldConfig{
					Type: types.GraphQLString,
					Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
						resolvedContext = p.Source.(map[string]interface{})
						return resolvedContext
					},
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

	// parse query
	ast := testutil.Parse(t, query)

	// execute
	ep := executor.ExecuteParams{
		Schema: schema,
		Root:   data,
		AST:    ast,
	}
	result := testutil.Execute(t, ep)
	if len(result.Errors) > 0 {
		t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
	}

	expected := "thing"
	if resolvedContext["contextThing"] != expected {
		t.Fatalf("Expected context.contextThing to equal %v, got %v", expected, resolvedContext["contextThing"])
	}
}
Example #15
0
func TestThrowsIfNoOperationIsProvidedWithMultipleOperations(t *testing.T) {

	doc := `query Example { a } query OtherExample { a }`
	data := map[string]interface{}{
		"a": "b",
	}

	expectedErrors := []graphqlerrors.GraphQLFormattedError{
		graphqlerrors.GraphQLFormattedError{
			Message:   "Must provide operation name if query contains multiple operations.",
			Locations: []location.SourceLocation{},
		},
	}

	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Type",
			Fields: types.GraphQLFieldConfigMap{
				"a": &types.GraphQLFieldConfig{
					Type: types.GraphQLString,
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

	// parse query
	ast := testutil.Parse(t, doc)

	// execute
	ep := executor.ExecuteParams{
		Schema: schema,
		AST:    ast,
		Root:   data,
	}
	result := testutil.Execute(t, ep)
	if len(result.Errors) != 1 {
		t.Fatalf("wrong result, expected len(1) unexpected len: %v", len(result.Errors))
	}
	if result.Data != nil {
		t.Fatalf("wrong result, expected nil result.Data, got %v", result.Data)
	}
	if !reflect.DeepEqual(expectedErrors, result.Errors) {
		t.Fatalf("unexpected result, Diff: %v", testutil.Diff(expectedErrors, result.Errors))
	}
}
Example #16
0
func TestDoesNotIncludeIllegalFieldsInOutput(t *testing.T) {

	doc := `mutation M {
      thisIsIllegalDontIncludeMe
    }`

	expected := &types.GraphQLResult{
		Data: map[string]interface{}{},
	}

	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Q",
			Fields: types.GraphQLFieldConfigMap{
				"a": &types.GraphQLFieldConfig{
					Type: types.GraphQLString,
				},
			},
		}),
		Mutation: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "M",
			Fields: types.GraphQLFieldConfigMap{
				"c": &types.GraphQLFieldConfig{
					Type: types.GraphQLString,
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

	// parse query
	ast := testutil.Parse(t, doc)

	// execute
	ep := executor.ExecuteParams{
		Schema: schema,
		AST:    ast,
	}
	result := testutil.Execute(t, ep)
	if len(result.Errors) != 0 {
		t.Fatalf("wrong result, expected len(%v) errors, got len(%v)", len(expected.Errors), len(result.Errors))
	}
	if !reflect.DeepEqual(expected, result) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
	}
}
Example #17
0
func TestFailsToExecuteQueryContainingATypeDefinition(t *testing.T) {

	query := `
      { foo }

      type Query { foo: String }
	`
	expected := &types.GraphQLResult{
		Data: nil,
		Errors: []graphqlerrors.GraphQLFormattedError{
			graphqlerrors.GraphQLFormattedError{
				Message:   "GraphQL cannot execute a request containing a ObjectTypeDefinition",
				Locations: []location.SourceLocation{},
			},
		},
	}

	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Query",
			Fields: types.GraphQLFieldConfigMap{
				"foo": &types.GraphQLFieldConfig{
					Type: types.GraphQLString,
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

	// parse query
	ast := testutil.Parse(t, query)

	// execute
	ep := executor.ExecuteParams{
		Schema: schema,
		AST:    ast,
	}
	result := testutil.Execute(t, ep)
	if len(result.Errors) != 1 {
		t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
	}
	if !reflect.DeepEqual(expected, result) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
	}
}
func TestTypeSystem_SchemaMustHaveObjectRootTypes_AcceptsASchemaWhoseQueryAndMutationTypesAreObjectType(t *testing.T) {
	mutationObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Mutation",
		Fields: types.GraphQLFieldConfigMap{
			"edit": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	_, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query:    someObjectType,
		Mutation: mutationObject,
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}
func schemaWithInputObject(ttype types.GraphQLInputType) (types.GraphQLSchema, error) {
	return types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Query",
			Fields: types.GraphQLFieldConfigMap{
				"f": &types.GraphQLFieldConfig{
					Type: types.GraphQLString,
					Args: types.GraphQLFieldConfigArgumentMap{
						"args": &types.GraphQLArgumentConfig{
							Type: ttype,
						},
					},
				},
			},
		}),
	})
}
Example #20
0
func checkList(t *testing.T, testType types.GraphQLType, testData interface{}, expected *types.GraphQLResult) {
	data := map[string]interface{}{
		"test": testData,
	}

	dataType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "DataType",
		Fields: types.GraphQLFieldConfigMap{
			"test": &types.GraphQLFieldConfig{
				Type: testType,
			},
		},
	})
	dataType.AddFieldConfig("nest", &types.GraphQLFieldConfig{
		Type: dataType,
		Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
			return data
		},
	})

	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: dataType,
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

	// parse query
	ast := testutil.Parse(t, `{ nest { test } }`)

	// execute
	ep := executor.ExecuteParams{
		Schema: schema,
		AST:    ast,
		Root:   data,
	}
	result := testutil.Execute(t, ep)
	if len(expected.Errors) != len(result.Errors) {
		t.Fatalf("wrong result, Diff: %v", testutil.Diff(expected.Errors, result.Errors))
	}
	if !reflect.DeepEqual(expected, result) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
	}

}
func TestIntrospection_FailsAsExpectedOnThe__TypeRootFieldWithoutAnArg(t *testing.T) {

	testType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "TestType",
		Fields: types.GraphQLFieldConfigMap{
			"testField": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: testType,
	})
	if err != nil {
		t.Fatalf("Error creating GraphQLSchema: %v", err.Error())
	}
	query := `
      {
        __type {
          name
        }
      }
    `
	expected := &types.GraphQLResult{
		Errors: []graphqlerrors.GraphQLFormattedError{
			graphqlerrors.GraphQLFormattedError{
				Message: `Field "__type" argument "name" of type "String!" ` +
					`is required but not provided.`,
				Locations: []location.SourceLocation{
					location.SourceLocation{Line: 3, Column: 9},
				},
			},
		},
	}
	result := graphql(t, gql.GraphqlParams{
		Schema:        schema,
		RequestString: query,
	})
	t.Skipf("Pending `validator` implementation")
	if !reflect.DeepEqual(expected, result) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
	}
}
func TestTypeSystem_DefinitionExample_IncludesInterfacesThunkSubtypesInTheTypeMap(t *testing.T) {

	someInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{
		Name: "SomeInterface",
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLInt,
			},
		},
	})

	someSubType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "SomeSubtype",
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLInt,
			},
		},
		Interfaces: (types.GraphQLInterfacesThunk)(func() []*types.GraphQLInterfaceType {
			return []*types.GraphQLInterfaceType{someInterface}
		}),
		IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool {
			return true
		},
	})
	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Query",
			Fields: types.GraphQLFieldConfigMap{
				"iface": &types.GraphQLFieldConfig{
					Type: someInterface,
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("unexpected error, got: %v", err)
	}
	if schema.GetType("SomeSubtype") != someSubType {
		t.Fatalf(`schema.GetType("SomeSubtype") expected to equal someSubType, got: %v`, schema.GetType("SomeSubtype"))
	}
}
Example #23
0
func TestBasicGraphQLExample(t *testing.T) {
	// taken from `graphql-js` README

	helloFieldResolved := func(ctx context.Context, p types.GQLFRParams) interface{} {
		return "world"
	}

	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "RootQueryType",
			Fields: types.GraphQLFieldConfigMap{
				"hello": &types.GraphQLFieldConfig{
					Description: "Returns `world`",
					Type:        types.GraphQLString,
					Resolve:     helloFieldResolved,
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("wrong result, unexpected errors: %v", err.Error())
	}
	query := "{ hello }"
	var expected interface{}
	expected = map[string]interface{}{
		"hello": "world",
	}

	resultChannel := make(chan *types.GraphQLResult)
	go Graphql(GraphqlParams{
		Schema:        schema,
		RequestString: query,
	}, resultChannel)
	result := <-resultChannel
	if len(result.Errors) > 0 {
		t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
	}
	if !reflect.DeepEqual(result.Data, expected) {
		t.Fatalf("wrong result, query: %v, graphql result diff: %v", query, testutil.Diff(expected, result))
	}

}
func schemaWithUnionOfType(ttype *types.GraphQLObjectType) (types.GraphQLSchema, error) {

	badObjectType := types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{
		Name: "BadUnion",
		ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType {
			return nil
		},
		Types: []*types.GraphQLObjectType{ttype},
	})
	return types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Query",
			Fields: types.GraphQLFieldConfigMap{
				"f": &types.GraphQLFieldConfig{
					Type: badObjectType,
				},
			},
		}),
	})
}
func TestTypeSystem_DefinitionExample_IncludesNestedInputObjectsInTheMap(t *testing.T) {
	nestedInputObject := types.NewGraphQLInputObjectType(types.InputObjectConfig{
		Name: "NestedInputObject",
		Fields: types.InputObjectConfigFieldMap{
			"value": &types.InputObjectFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	someInputObject := types.NewGraphQLInputObjectType(types.InputObjectConfig{
		Name: "SomeInputObject",
		Fields: types.InputObjectConfigFieldMap{
			"nested": &types.InputObjectFieldConfig{
				Type: nestedInputObject,
			},
		},
	})
	someMutation := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "SomeMutation",
		Fields: types.GraphQLFieldConfigMap{
			"mutateSomething": &types.GraphQLFieldConfig{
				Type: blogArticle,
				Args: types.GraphQLFieldConfigArgumentMap{
					"input": &types.GraphQLArgumentConfig{
						Type: someInputObject,
					},
				},
			},
		},
	})
	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query:    blogQuery,
		Mutation: someMutation,
	})
	if err != nil {
		t.Fatalf("unexpected error, got: %v", err)
	}
	if schema.GetType("NestedInputObject") != nestedInputObject {
		t.Fatalf(`schema.GetType("NestedInputObject") expected to equal nestedInputObject, got: %v`, schema.GetType("NestedInputObject"))
	}
}
func schemaWithInterfaceFieldOfType(ttype types.GraphQLType) (types.GraphQLSchema, error) {

	badInterfaceType := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{
		Name: "BadInterface",
		Fields: types.GraphQLFieldConfigMap{
			"badField": &types.GraphQLFieldConfig{
				Type: ttype,
			},
		},
	})
	return types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Query",
			Fields: types.GraphQLFieldConfigMap{
				"f": &types.GraphQLFieldConfig{
					Type: badInterfaceType,
				},
			},
		}),
	})
}
func schemaWithObjectFieldOfType(fieldType types.GraphQLInputType) (types.GraphQLSchema, error) {

	badObjectType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "BadObject",
		Fields: types.GraphQLFieldConfigMap{
			"badField": &types.GraphQLFieldConfig{
				Type: fieldType,
			},
		},
	})
	return types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Query",
			Fields: types.GraphQLFieldConfigMap{
				"f": &types.GraphQLFieldConfig{
					Type: badObjectType,
				},
			},
		}),
	})
}
func schemaWithObjectImplementingType(implementedType *types.GraphQLInterfaceType) (types.GraphQLSchema, error) {

	badObjectType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:       "BadObject",
		Interfaces: []*types.GraphQLInterfaceType{implementedType},
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	return types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Query",
			Fields: types.GraphQLFieldConfigMap{
				"f": &types.GraphQLFieldConfig{
					Type: badObjectType,
				},
			},
		}),
	})
}
func TestIntrospection_SupportsThe__TypeRootField(t *testing.T) {

	testType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "TestType",
		Fields: types.GraphQLFieldConfigMap{
			"testField": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: testType,
	})
	if err != nil {
		t.Fatalf("Error creating GraphQLSchema: %v", err.Error())
	}
	query := `
      {
        __type(name: "TestType") {
          name
        }
      }
    `
	expected := &types.GraphQLResult{
		Data: map[string]interface{}{
			"__type": map[string]interface{}{
				"name": "TestType",
			},
		},
	}
	result := graphql(t, gql.GraphqlParams{
		Schema:        schema,
		RequestString: query,
	})
	if !reflect.DeepEqual(expected, result) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
	}
}
func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichDefinesAnObjectTypeTwice(t *testing.T) {

	a := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "SameName",
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	b := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "SameName",
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	queryType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Query",
		Fields: types.GraphQLFieldConfigMap{
			"a": &types.GraphQLFieldConfig{
				Type: a,
			},
			"b": &types.GraphQLFieldConfig{
				Type: b,
			},
		},
	})
	_, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: queryType,
	})
	expectedError := `Schema must contain unique named types but contains multiple types named "SameName".`
	if err == nil || err.Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, err)
	}
}