示例#1
0
func TestTypeSystem_ObjectInterfacesMustBeArray_AcceptsAnObjectTypeWithInterfacesAsFunctionReturningAnArray(t *testing.T) {
	anotherInterfaceType := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {
			return nil
		},
		Fields: graphql.FieldConfigMap{
			"f": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
	})
	_, err := schemaWithFieldType(graphql.NewObject(graphql.ObjectConfig{
		Name:       "SomeObject",
		Interfaces: []*graphql.Interface{anotherInterfaceType},
		Fields: graphql.FieldConfigMap{
			"f": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
	}))
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}
示例#2
0
func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceTypeDefiningResolveTypeWithImplementingTypeDefiningIsTypeOf(t *testing.T) {

	anotherInterfaceType := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {
			return nil
		},
		Fields: graphql.FieldConfigMap{
			"f": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
	})
	_, err := schemaWithFieldType(graphql.NewObject(graphql.ObjectConfig{
		Name:       "SomeObject",
		Interfaces: []*graphql.Interface{anotherInterfaceType},
		IsTypeOf: func(value interface{}, info graphql.ResolveInfo) bool {
			return true
		},
		Fields: graphql.FieldConfigMap{
			"f": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
	}))
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}
示例#3
0
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWithAnEquivalentlyModifiedInterfaceField(t *testing.T) {
	anotherInterface := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {
			return nil
		},
		Fields: graphql.FieldConfigMap{
			"field": &graphql.FieldConfig{
				Type: graphql.NewNonNull(graphql.NewList(graphql.String)),
			},
		},
	})
	anotherObject := graphql.NewObject(graphql.ObjectConfig{
		Name:       "AnotherObject",
		Interfaces: []*graphql.Interface{anotherInterface},
		Fields: graphql.FieldConfigMap{
			"field": &graphql.FieldConfig{
				Type: graphql.NewNonNull(graphql.NewList(graphql.String)),
			},
		},
	})
	_, err := schemaWithObjectFieldOfType(anotherObject)
	if err != nil {
		t.Fatalf(`unexpected error: %v for type "%v"`, err, anotherObject)
	}
}
示例#4
0
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWithADifferentlyModifiedInterfaceFieldType(t *testing.T) {
	anotherInterface := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {
			return nil
		},
		Fields: graphql.FieldConfigMap{
			"field": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
	})
	anotherObject := graphql.NewObject(graphql.ObjectConfig{
		Name:       "AnotherObject",
		Interfaces: []*graphql.Interface{anotherInterface},
		Fields: graphql.FieldConfigMap{
			"field": &graphql.FieldConfig{
				Type: graphql.NewNonNull(graphql.String),
			},
		},
	})
	_, err := schemaWithObjectFieldOfType(anotherObject)
	expectedError := `AnotherInterface.field expects type "String" but AnotherObject.field provides type "String!".`
	if err == nil || err.Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, err)
	}
}
示例#5
0
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectMissingAnInterfaceArgument(t *testing.T) {
	anotherInterface := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {
			return nil
		},
		Fields: graphql.FieldConfigMap{
			"field": &graphql.FieldConfig{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"input": &graphql.ArgumentConfig{
						Type: graphql.String,
					},
				},
			},
		},
	})
	anotherObject := graphql.NewObject(graphql.ObjectConfig{
		Name:       "AnotherObject",
		Interfaces: []*graphql.Interface{anotherInterface},
		Fields: graphql.FieldConfigMap{
			"field": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
	})
	_, err := schemaWithObjectFieldOfType(anotherObject)
	expectedError := `AnotherInterface.field expects argument "input" but AnotherObject.field does not provide it.`
	if err == nil || err.Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, err)
	}
}
示例#6
0
func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichHaveSameNamedObjectsImplementingAnInterface(t *testing.T) {

	anotherInterface := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {
			return nil
		},
		Fields: graphql.FieldConfigMap{
			"f": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
	})
	_ = graphql.NewObject(graphql.ObjectConfig{
		Name: "BadObject",
		Interfaces: []*graphql.Interface{
			anotherInterface,
		},
		Fields: graphql.FieldConfigMap{
			"f": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
	})
	_ = graphql.NewObject(graphql.ObjectConfig{
		Name: "BadObject",
		Interfaces: []*graphql.Interface{
			anotherInterface,
		},
		Fields: graphql.FieldConfigMap{
			"f": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
	})
	queryType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.FieldConfigMap{
			"iface": &graphql.FieldConfig{
				Type: anotherInterface,
			},
		},
	})
	_, err := graphql.NewSchema(graphql.SchemaConfig{
		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)
	}
}
示例#7
0
func TestTypeSystem_ObjectsCanOnlyImplementInterfaces_AcceptsAnObjectImplementingAnInterface(t *testing.T) {
	anotherInterfaceType := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {
			return nil
		},
		Fields: graphql.FieldConfigMap{
			"f": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
	})
	_, err := schemaWithObjectImplementingType(anotherInterfaceType)
	if err != nil {
		t.Fatalf(`unexpected error: %v"`, err)
	}
}
示例#8
0
func TestTypeSystem_DefinitionExample_IncludesInterfacesThunkSubtypesInTheTypeMap(t *testing.T) {

	someInterface := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "SomeInterface",
		Fields: graphql.FieldConfigMap{
			"f": &graphql.FieldConfig{
				Type: graphql.Int,
			},
		},
	})

	someSubType := graphql.NewObject(graphql.ObjectConfig{
		Name: "SomeSubtype",
		Fields: graphql.FieldConfigMap{
			"f": &graphql.FieldConfig{
				Type: graphql.Int,
			},
		},
		Interfaces: (graphql.InterfacesThunk)(func() []*graphql.Interface {
			return []*graphql.Interface{someInterface}
		}),
		IsTypeOf: func(value interface{}, info graphql.ResolveInfo) bool {
			return true
		},
	})
	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "Query",
			Fields: graphql.FieldConfigMap{
				"iface": &graphql.FieldConfig{
					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"))
	}
}
示例#9
0
func schemaWithInterfaceFieldOfType(ttype graphql.Type) (graphql.Schema, error) {

	badInterfaceType := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "BadInterface",
		Fields: graphql.FieldConfigMap{
			"badField": &graphql.FieldConfig{
				Type: ttype,
			},
		},
	})
	return graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "Query",
			Fields: graphql.FieldConfigMap{
				"f": &graphql.FieldConfig{
					Type: badInterfaceType,
				},
			},
		}),
	})
}
示例#10
0
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWhichImplementsAnInterfaceAlongWithMoreFields(t *testing.T) {
	anotherInterface := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {
			return nil
		},
		Fields: graphql.FieldConfigMap{
			"field": &graphql.FieldConfig{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"input": &graphql.ArgumentConfig{
						Type: graphql.String,
					},
				},
			},
		},
	})
	anotherObject := graphql.NewObject(graphql.ObjectConfig{
		Name:       "AnotherObject",
		Interfaces: []*graphql.Interface{anotherInterface},
		Fields: graphql.FieldConfigMap{
			"field": &graphql.FieldConfig{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"input": &graphql.ArgumentConfig{
						Type: graphql.String,
					},
				},
			},
			"anotherfield": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
	})
	_, err := schemaWithObjectFieldOfType(anotherObject)
	if err != nil {
		t.Fatalf(`unexpected error: %v for type "%v"`, err, anotherObject)
	}
}
示例#11
0
func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) {

	var dogType *graphql.Object
	var catType *graphql.Object
	var humanType *graphql.Object
	petType := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "Pet",
		Fields: graphql.FieldConfigMap{
			"name": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
		ResolveType: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {
			if _, ok := value.(*testCat); ok {
				return catType
			}
			if _, ok := value.(*testDog); ok {
				return dogType
			}
			if _, ok := value.(*testHuman); ok {
				return humanType
			}
			return nil
		},
	})

	humanType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Human",
		Fields: graphql.FieldConfigMap{
			"name": &graphql.FieldConfig{
				Type: graphql.String,
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if human, ok := p.Source.(*testHuman); ok {
						return human.Name
					}
					return nil
				},
			},
		},
	})
	dogType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Dog",
		Interfaces: []*graphql.Interface{
			petType,
		},
		IsTypeOf: func(value interface{}, info graphql.ResolveInfo) bool {
			_, ok := value.(*testDog)
			return ok
		},
		Fields: graphql.FieldConfigMap{
			"name": &graphql.FieldConfig{
				Type: graphql.String,
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if dog, ok := p.Source.(*testDog); ok {
						return dog.Name
					}
					return nil
				},
			},
			"woofs": &graphql.FieldConfig{
				Type: graphql.Boolean,
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if dog, ok := p.Source.(*testDog); ok {
						return dog.Woofs
					}
					return nil
				},
			},
		},
	})
	catType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Cat",
		Interfaces: []*graphql.Interface{
			petType,
		},
		IsTypeOf: func(value interface{}, info graphql.ResolveInfo) bool {
			_, ok := value.(*testCat)
			return ok
		},
		Fields: graphql.FieldConfigMap{
			"name": &graphql.FieldConfig{
				Type: graphql.String,
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if cat, ok := p.Source.(*testCat); ok {
						return cat.Name
					}
					return nil
				},
			},
			"meows": &graphql.FieldConfig{
				Type: graphql.Boolean,
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if cat, ok := p.Source.(*testCat); ok {
						return cat.Meows
					}
					return nil
				},
			},
		},
	})
	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "Query",
			Fields: graphql.FieldConfigMap{
				"pets": &graphql.FieldConfig{
					Type: graphql.NewList(petType),
					Resolve: func(p graphql.GQLFRParams) interface{} {
						return []interface{}{
							&testDog{"Odie", true},
							&testCat{"Garfield", false},
							&testHuman{"Jon"},
						}
					},
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

	query := `{
      pets {
        name
        ... on Dog {
          woofs
        }
        ... on Cat {
          meows
        }
      }
    }`

	expected := &graphql.Result{
		Data: map[string]interface{}{
			"pets": []interface{}{
				map[string]interface{}{
					"name":  "Odie",
					"woofs": bool(true),
				},
				map[string]interface{}{
					"name":  "Garfield",
					"meows": bool(false),
				},
				nil,
			},
		},
		Errors: []gqlerrors.FormattedError{
			gqlerrors.FormattedError{
				Message:   `Runtime Object type "Human" is not a possible type for "Pet".`,
				Locations: []location.SourceLocation{},
			},
		},
	}

	resultChannel := make(chan *graphql.Result)

	go graphql.Graphql(graphql.Params{
		Schema:        schema,
		RequestString: query,
	}, resultChannel)
	result := <-resultChannel
	if len(result.Errors) == 0 {
		t.Fatalf("wrong result, expected errors: %v, got: %v", len(expected.Errors), len(result.Errors))
	}
	if !reflect.DeepEqual(expected, result) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
	}
}
示例#12
0
})
var someUnionType = graphql.NewUnion(graphql.UnionConfig{
	Name: "SomeUnion",
	ResolveType: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {
		return nil
	},
	Types: []*graphql.Object{
		someObjectType,
	},
})
var someInterfaceType = graphql.NewInterface(graphql.InterfaceConfig{
	Name: "SomeInterface",
	ResolveType: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {
		return nil
	},
	Fields: graphql.FieldConfigMap{
		"f": &graphql.FieldConfig{
			Type: graphql.String,
		},
	},
})
var someEnumType = graphql.NewEnum(graphql.EnumConfig{
	Name: "SomeEnum",
	Values: graphql.EnumValueConfigMap{
		"ONLY": &graphql.EnumValueConfig{},
	},
})
var someInputObject = graphql.NewInputObject(graphql.InputObjectConfig{
	Name: "SomeInputObject",
	Fields: graphql.InputObjectConfigFieldMap{
		"f": &graphql.InputObjectFieldConfig{
示例#13
0
func TestUnionIntersectionTypes_GetsExecutionInfoInResolver(t *testing.T) {

	var encounteredSchema *graphql.Schema
	var encounteredRootValue interface{}

	var personType2 *graphql.Object

	namedType2 := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "Named",
		Fields: graphql.FieldConfigMap{
			"name": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
		ResolveType: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {
			encounteredSchema = &info.Schema
			encounteredRootValue = info.RootValue
			return personType2
		},
	})

	personType2 = graphql.NewObject(graphql.ObjectConfig{
		Name: "Person",
		Interfaces: []*graphql.Interface{
			namedType2,
		},
		Fields: graphql.FieldConfigMap{
			"name": &graphql.FieldConfig{
				Type: graphql.String,
			},
			"friends": &graphql.FieldConfig{
				Type: graphql.NewList(namedType2),
			},
		},
	})

	schema2, _ := graphql.NewSchema(graphql.SchemaConfig{
		Query: personType2,
	})

	john2 := &testPerson{
		Name: "John",
		Friends: []testNamedType{
			liz,
		},
	}

	doc := `{ name, friends { name } }`
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"name": "John",
			"friends": []interface{}{
				map[string]interface{}{
					"name": "Liz",
				},
			},
		},
	}
	// parse query
	ast := testutil.TestParse(t, doc)

	// execute
	ep := graphql.ExecuteParams{
		Schema: schema2,
		AST:    ast,
		Root:   john2,
	}
	result := testutil.TestExecute(t, ep)
	if len(result.Errors) != len(expected.Errors) {
		t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors))
	}
	if !reflect.DeepEqual(expected, result) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
	}
}
示例#14
0
type testCat2 struct {
	Name  string `json:"name"`
	Meows bool   `json:"meows"`
}

type testPerson struct {
	Name    string          `json:"name"`
	Pets    []testPet       `json:"pets"`
	Friends []testNamedType `json:"friends"`
}

var namedType = graphql.NewInterface(graphql.InterfaceConfig{
	Name: "Named",
	Fields: graphql.FieldConfigMap{
		"name": &graphql.FieldConfig{
			Type: graphql.String,
		},
	},
})
var dogType = graphql.NewObject(graphql.ObjectConfig{
	Name: "Dog",
	Interfaces: []*graphql.Interface{
		namedType,
	},
	Fields: graphql.FieldConfigMap{
		"name": &graphql.FieldConfig{
			Type: graphql.String,
		},
		"barks": &graphql.FieldConfig{
			Type: graphql.Boolean,
		},
示例#15
0
	Name: "Mutation",
	Fields: graphql.FieldConfigMap{
		"writeArticle": &graphql.FieldConfig{
			Type: blogArticle,
		},
	},
})

var objectType = graphql.NewObject(graphql.ObjectConfig{
	Name: "Object",
	IsTypeOf: func(value interface{}, info graphql.ResolveInfo) bool {
		return true
	},
})
var interfaceType = graphql.NewInterface(graphql.InterfaceConfig{
	Name: "Interface",
})
var unionType = graphql.NewUnion(graphql.UnionConfig{
	Name: "Union",
	Types: []*graphql.Object{
		objectType,
	},
})
var enumType = graphql.NewEnum(graphql.EnumConfig{
	Name: "Enum",
	Values: graphql.EnumValueConfigMap{
		"foo": &graphql.EnumValueConfig{},
	},
})
var inputObjectType = graphql.NewInputObject(graphql.InputObjectConfig{
	Name: "InputObject",
示例#16
0
func init() {
	Luke = StarWarsChar{
		Id:         "1000",
		Name:       "Luke Skywalker",
		AppearsIn:  []int{4, 5, 6},
		HomePlanet: "Tatooine",
	}
	Vader = StarWarsChar{
		Id:         "1001",
		Name:       "Darth Vader",
		AppearsIn:  []int{4, 5, 6},
		HomePlanet: "Tatooine",
	}
	Han = StarWarsChar{
		Id:        "1002",
		Name:      "Han Solo",
		AppearsIn: []int{4, 5, 6},
	}
	Leia = StarWarsChar{
		Id:         "1003",
		Name:       "Leia Organa",
		AppearsIn:  []int{4, 5, 6},
		HomePlanet: "Alderaa",
	}
	Tarkin = StarWarsChar{
		Id:        "1004",
		Name:      "Wilhuff Tarkin",
		AppearsIn: []int{4},
	}
	Threepio = StarWarsChar{
		Id:              "2000",
		Name:            "C-3PO",
		AppearsIn:       []int{4, 5, 6},
		PrimaryFunction: "Protocol",
	}
	Artoo = StarWarsChar{
		Id:              "2001",
		Name:            "R2-D2",
		AppearsIn:       []int{4, 5, 6},
		PrimaryFunction: "Astromech",
	}
	Luke.Friends = append(Luke.Friends, []StarWarsChar{Han, Leia, Threepio, Artoo}...)
	Vader.Friends = append(Luke.Friends, []StarWarsChar{Tarkin}...)
	Han.Friends = append(Han.Friends, []StarWarsChar{Luke, Leia, Artoo}...)
	Leia.Friends = append(Leia.Friends, []StarWarsChar{Luke, Han, Threepio, Artoo}...)
	Tarkin.Friends = append(Tarkin.Friends, []StarWarsChar{Vader}...)
	Threepio.Friends = append(Threepio.Friends, []StarWarsChar{Luke, Han, Leia, Artoo}...)
	Artoo.Friends = append(Artoo.Friends, []StarWarsChar{Luke, Han, Leia}...)
	HumanData = map[int]StarWarsChar{
		1000: Luke,
		1001: Vader,
		1002: Han,
		1003: Leia,
		1004: Tarkin,
	}
	DroidData = map[int]StarWarsChar{
		2000: Threepio,
		2001: Artoo,
	}

	episodeEnum := graphql.NewEnum(graphql.EnumConfig{
		Name:        "Episode",
		Description: "One of the films in the Star Wars Trilogy",
		Values: graphql.EnumValueConfigMap{
			"NEWHOPE": &graphql.EnumValueConfig{
				Value:       4,
				Description: "Released in 1977.",
			},
			"EMPIRE": &graphql.EnumValueConfig{
				Value:       5,
				Description: "Released in 1980.",
			},
			"JEDI": &graphql.EnumValueConfig{
				Value:       6,
				Description: "Released in 1983.",
			},
		},
	})

	characterInterface := graphql.NewInterface(graphql.InterfaceConfig{
		Name:        "Character",
		Description: "A character in the Star Wars Trilogy",
		Fields: graphql.FieldConfigMap{
			"id": &graphql.FieldConfig{
				Type:        graphql.NewNonNull(graphql.String),
				Description: "The id of the character.",
			},
			"name": &graphql.FieldConfig{
				Type:        graphql.String,
				Description: "The name of the character.",
			},
			"appearsIn": &graphql.FieldConfig{
				Type:        graphql.NewList(episodeEnum),
				Description: "Which movies they appear in.",
			},
		},
		ResolveType: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {
			if character, ok := value.(StarWarsChar); ok {
				id, _ := strconv.Atoi(character.Id)
				human := GetHuman(id)
				if human.Id != "" {
					return humanType
				}
			}
			return droidType
		},
	})
	characterInterface.AddFieldConfig("friends", &graphql.FieldConfig{
		Type:        graphql.NewList(characterInterface),
		Description: "The friends of the character, or an empty list if they have none.",
	})

	humanType = graphql.NewObject(graphql.ObjectConfig{
		Name:        "Human",
		Description: "A humanoid creature in the Star Wars universe.",
		Fields: graphql.FieldConfigMap{
			"id": &graphql.FieldConfig{
				Type:        graphql.NewNonNull(graphql.String),
				Description: "The id of the human.",
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Id
					}
					return nil
				},
			},
			"name": &graphql.FieldConfig{
				Type:        graphql.String,
				Description: "The name of the human.",
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Name
					}
					return nil
				},
			},
			"friends": &graphql.FieldConfig{
				Type:        graphql.NewList(characterInterface),
				Description: "The friends of the human, or an empty list if they have none.",
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Friends
					}
					return []interface{}{}
				},
			},
			"appearsIn": &graphql.FieldConfig{
				Type:        graphql.NewList(episodeEnum),
				Description: "Which movies they appear in.",
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.AppearsIn
					}
					return nil
				},
			},
			"homePlanet": &graphql.FieldConfig{
				Type:        graphql.String,
				Description: "The home planet of the human, or null if unknown.",
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.HomePlanet
					}
					return nil
				},
			},
		},
		Interfaces: []*graphql.Interface{
			characterInterface,
		},
	})
	droidType = graphql.NewObject(graphql.ObjectConfig{
		Name:        "Droid",
		Description: "A mechanical creature in the Star Wars universe.",
		Fields: graphql.FieldConfigMap{
			"id": &graphql.FieldConfig{
				Type:        graphql.NewNonNull(graphql.String),
				Description: "The id of the droid.",
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.Id
					}
					return nil
				},
			},
			"name": &graphql.FieldConfig{
				Type:        graphql.String,
				Description: "The name of the droid.",
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.Name
					}
					return nil
				},
			},
			"friends": &graphql.FieldConfig{
				Type:        graphql.NewList(characterInterface),
				Description: "The friends of the droid, or an empty list if they have none.",
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						friends := []map[string]interface{}{}
						for _, friend := range droid.Friends {
							friends = append(friends, map[string]interface{}{
								"name": friend.Name,
								"id":   friend.Id,
							})
						}
						return droid.Friends
					}
					return []interface{}{}
				},
			},
			"appearsIn": &graphql.FieldConfig{
				Type:        graphql.NewList(episodeEnum),
				Description: "Which movies they appear in.",
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.AppearsIn
					}
					return nil
				},
			},
			"primaryFunction": &graphql.FieldConfig{
				Type:        graphql.String,
				Description: "The primary function of the droid.",
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.PrimaryFunction
					}
					return nil
				},
			},
		},
		Interfaces: []*graphql.Interface{
			characterInterface,
		},
	})

	queryType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.FieldConfigMap{
			"hero": &graphql.FieldConfig{
				Type: characterInterface,
				Args: graphql.FieldConfigArgument{
					"episode": &graphql.ArgumentConfig{
						Description: "If omitted, returns the hero of the whole saga. If " +
							"provided, returns the hero of that particular episode.",
						Type: episodeEnum,
					},
				},
				Resolve: func(p graphql.GQLFRParams) (r interface{}) {
					return GetHero(p.Args["episode"])
				},
			},
			"human": &graphql.FieldConfig{
				Type: humanType,
				Args: graphql.FieldConfigArgument{
					"id": &graphql.ArgumentConfig{
						Description: "id of the human",
						Type:        graphql.NewNonNull(graphql.String),
					},
				},
				Resolve: func(p graphql.GQLFRParams) (r interface{}) {
					return GetHuman(p.Args["id"].(int))
				},
			},
			"droid": &graphql.FieldConfig{
				Type: droidType,
				Args: graphql.FieldConfigArgument{
					"id": &graphql.ArgumentConfig{
						Description: "id of the droid",
						Type:        graphql.NewNonNull(graphql.String),
					},
				},
				Resolve: func(p graphql.GQLFRParams) (r interface{}) {
					return GetDroid(p.Args["id"].(int))
				},
			},
		},
	})
	StarWarsSchema, _ = graphql.NewSchema(graphql.SchemaConfig{
		Query: queryType,
	})
}
示例#17
0
func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) {

	petType := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "Pet",
		Fields: graphql.FieldConfigMap{
			"name": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
	})

	// ie declare that Dog belongs to Pet interface
	_ = graphql.NewObject(graphql.ObjectConfig{
		Name: "Dog",
		Interfaces: []*graphql.Interface{
			petType,
		},
		IsTypeOf: func(value interface{}, info graphql.ResolveInfo) bool {
			_, ok := value.(*testDog)
			return ok
		},
		Fields: graphql.FieldConfigMap{
			"name": &graphql.FieldConfig{
				Type: graphql.String,
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if dog, ok := p.Source.(*testDog); ok {
						return dog.Name
					}
					return nil
				},
			},
			"woofs": &graphql.FieldConfig{
				Type: graphql.Boolean,
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if dog, ok := p.Source.(*testDog); ok {
						return dog.Woofs
					}
					return nil
				},
			},
		},
	})
	// ie declare that Cat belongs to Pet interface
	_ = graphql.NewObject(graphql.ObjectConfig{
		Name: "Cat",
		Interfaces: []*graphql.Interface{
			petType,
		},
		IsTypeOf: func(value interface{}, info graphql.ResolveInfo) bool {
			_, ok := value.(*testCat)
			return ok
		},
		Fields: graphql.FieldConfigMap{
			"name": &graphql.FieldConfig{
				Type: graphql.String,
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if cat, ok := p.Source.(*testCat); ok {
						return cat.Name
					}
					return nil
				},
			},
			"meows": &graphql.FieldConfig{
				Type: graphql.Boolean,
				Resolve: func(p graphql.GQLFRParams) interface{} {
					if cat, ok := p.Source.(*testCat); ok {
						return cat.Meows
					}
					return nil
				},
			},
		},
	})
	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "Query",
			Fields: graphql.FieldConfigMap{
				"pets": &graphql.FieldConfig{
					Type: graphql.NewList(petType),
					Resolve: func(p graphql.GQLFRParams) interface{} {
						return []interface{}{
							&testDog{"Odie", true},
							&testCat{"Garfield", false},
						}
					},
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

	query := `{
      pets {
        name
        ... on Dog {
          woofs
        }
        ... on Cat {
          meows
        }
      }
    }`

	expected := &graphql.Result{
		Data: map[string]interface{}{
			"pets": []interface{}{
				map[string]interface{}{
					"name":  "Odie",
					"woofs": bool(true),
				},
				map[string]interface{}{
					"name":  "Garfield",
					"meows": bool(false),
				},
			},
		},
		Errors: nil,
	}

	resultChannel := make(chan *graphql.Result)

	go graphql.Graphql(graphql.Params{
		Schema:        schema,
		RequestString: query,
	}, resultChannel)
	result := <-resultChannel
	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))
	}
}