Exemplo n.º 1
0
func PluralIdentifyingRootField(config PluralIdentifyingRootFieldConfig) *graphql.Field {
	inputArgs := graphql.FieldConfigArgument{}
	if config.ArgName != "" {
		inputArgs[config.ArgName] = &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(config.InputType))),
		}
	}

	return &graphql.Field{
		Description: config.Description,
		Type:        graphql.NewList(config.OutputType),
		Args:        inputArgs,
		Resolve: func(p graphql.ResolveParams) (interface{}, error) {
			inputs, ok := p.Args[config.ArgName]
			if !ok {
				return nil, nil
			}

			if config.ResolveSingleInput == nil {
				return nil, nil
			}
			switch inputs := inputs.(type) {
			case []interface{}:
				res := []interface{}{}
				for _, input := range inputs {
					r := config.ResolveSingleInput(input)
					res = append(res, r)
				}
				return res, nil
			}
			return nil, nil
		},
	}
}
Exemplo n.º 2
0
func TestTypeSystem_DefinitionExample_StringifiesSimpleTypes(t *testing.T) {

	type Test struct {
		ttype    graphql.Type
		expected string
	}
	tests := []Test{
		{graphql.Int, "Int"},
		{blogArticle, "Article"},
		{interfaceType, "Interface"},
		{unionType, "Union"},
		{enumType, "Enum"},
		{inputObjectType, "InputObject"},
		{graphql.NewNonNull(graphql.Int), "Int!"},
		{graphql.NewList(graphql.Int), "[Int]"},
		{graphql.NewNonNull(graphql.NewList(graphql.Int)), "[Int]!"},
		{graphql.NewList(graphql.NewNonNull(graphql.Int)), "[Int!]"},
		{graphql.NewList(graphql.NewList(graphql.Int)), "[[Int]]"},
	}
	for _, test := range tests {
		ttypeStr := fmt.Sprintf("%v", test.ttype)
		if ttypeStr != test.expected {
			t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr)
		}
	}
}
Exemplo n.º 3
0
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWithAnEquivalentlyModifiedInterfaceField(t *testing.T) {
	anotherInterface := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			return nil
		},
		Fields: graphql.Fields{
			"field": &graphql.Field{
				Type: graphql.NewNonNull(graphql.NewList(graphql.String)),
			},
		},
	})
	anotherObject := graphql.NewObject(graphql.ObjectConfig{
		Name:       "AnotherObject",
		Interfaces: []*graphql.Interface{anotherInterface},
		Fields: graphql.Fields{
			"field": &graphql.Field{
				Type: graphql.NewNonNull(graphql.NewList(graphql.String)),
			},
		},
	})
	_, err := schemaWithObjectFieldOfType(anotherObject)
	if err != nil {
		t.Fatalf(`unexpected error: %v for type "%v"`, err, anotherObject)
	}
}
Exemplo n.º 4
0
func withModifiers(ttypes []graphql.Type) []graphql.Type {
	res := ttypes
	for _, ttype := range ttypes {
		res = append(res, graphql.NewList(ttype))
	}
	for _, ttype := range ttypes {
		res = append(res, graphql.NewNonNull(ttype))
	}
	for _, ttype := range ttypes {
		res = append(res, graphql.NewNonNull(graphql.NewList(ttype)))
	}
	return res
}
Exemplo n.º 5
0
func TestTypeSystem_ListMustAcceptGraphQLTypes_RejectsANilTypeAsItemTypeOfList(t *testing.T) {
	result := graphql.NewList(nil)
	expectedError := `Can only create List of a Type but got: <nil>.`
	if result.Error() == nil || result.Error().Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, result.Error())
	}
}
Exemplo n.º 6
0
func TestTypeSystem_DefinitionExample_IdentifiesOutputTypes(t *testing.T) {
	type Test struct {
		ttype    graphql.Type
		expected bool
	}
	tests := []Test{
		{graphql.Int, true},
		{objectType, true},
		{interfaceType, true},
		{unionType, true},
		{enumType, true},
		{inputObjectType, false},
	}
	for _, test := range tests {
		ttypeStr := fmt.Sprintf("%v", test.ttype)
		if graphql.IsOutputType(test.ttype) != test.expected {
			t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr)
		}
		if graphql.IsOutputType(graphql.NewList(test.ttype)) != test.expected {
			t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr)
		}
		if graphql.IsOutputType(graphql.NewNonNull(test.ttype)) != test.expected {
			t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr)
		}
	}
}
Exemplo n.º 7
0
func TestLists_NonNullListOfNonNullArrayOfFunc_ContainsNulls(t *testing.T) {
	ttype := graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(graphql.Int)))

	// `data` is a slice of functions that return values
	// Note that its uses the expected signature `func() interface{} {...}`
	data := []interface{}{
		func() interface{} {
			return 1
		},
		func() interface{} {
			return nil
		},
		func() interface{} {
			return 2
		},
	}
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": []interface{}{
					1, nil, 2,
				},
			},
		},
	}
	checkList(t, ttype, data, expected)
}
Exemplo n.º 8
0
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWithAListInterfaceFieldNonListType(t *testing.T) {
	anotherInterface := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			return nil
		},
		Fields: graphql.Fields{
			"field": &graphql.Field{
				Type: graphql.String,
			},
		},
	})
	anotherObject := graphql.NewObject(graphql.ObjectConfig{
		Name:       "AnotherObject",
		Interfaces: []*graphql.Interface{anotherInterface},
		Fields: graphql.Fields{
			"field": &graphql.Field{
				Type: graphql.NewList(graphql.String),
			},
		},
	})
	_, err := schemaWithFieldType(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)
	}
}
Exemplo n.º 9
0
func TestLists_NonNullListOfNonNullFunc_ReturnsNull(t *testing.T) {
	ttype := graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(graphql.Int)))

	// `data` is a function that return values
	// Note that its uses the expected signature `func() interface{} {...}`
	data := func() interface{} {
		return nil
	}
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"nest": nil,
		},
		Errors: []gqlerrors.FormattedError{
			{
				Message: "Cannot return null for non-nullable field DataType.test.",
				Locations: []location.SourceLocation{
					{
						Line:   1,
						Column: 10,
					},
				},
			},
		},
	}
	checkList(t, ttype, data, expected)
}
Exemplo n.º 10
0
func TestLists_NullableListOfNonNullObjects_ContainsNull(t *testing.T) {
	ttype := graphql.NewList(graphql.NewNonNull(graphql.Int))
	data := []interface{}{
		1, nil, 2,
	}
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": nil,
			},
		},
		Errors: []gqlerrors.FormattedError{
			{
				Message: "Cannot return null for non-nullable field DataType.test.",
				Locations: []location.SourceLocation{
					{
						Line:   1,
						Column: 10,
					},
				},
			},
		},
	}
	checkList(t, ttype, data, expected)
}
Exemplo n.º 11
0
func TestTypeSystem_NonNullMustAcceptGraphQLTypes_AcceptsAnTypeAsNullableTypeOfNonNull(t *testing.T) {
	nullableTypes := []graphql.Type{
		graphql.String,
		someScalarType,
		someObjectType,
		someUnionType,
		someInterfaceType,
		someEnumType,
		someInputObject,
		graphql.NewList(graphql.String),
		graphql.NewList(graphql.NewNonNull(graphql.String)),
	}
	for _, ttype := range nullableTypes {
		result := graphql.NewNonNull(ttype)
		if result.Error() != nil {
			t.Fatalf(`unexpected error: %v for type "%v"`, result.Error(), ttype)
		}
	}
}
Exemplo n.º 12
0
func TestLists_ListOfNullableObjects_ReturnsNull(t *testing.T) {
	ttype := graphql.NewList(graphql.Int)
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": nil,
			},
		},
	}
	checkList(t, ttype, nil, expected)
}
Exemplo n.º 13
0
func TestTypeSystem_ListMustAcceptGraphQLTypes_AcceptsAnTypeAsItemTypeOfList(t *testing.T) {
	testTypes := withModifiers([]graphql.Type{
		graphql.String,
		someScalarType,
		someEnumType,
		someObjectType,
		someUnionType,
		someInterfaceType,
	})
	for _, ttype := range testTypes {
		result := graphql.NewList(ttype)
		if result.Error() != nil {
			t.Fatalf(`unexpected error: %v for type "%v"`, result.Error(), ttype)
		}
	}
}
Exemplo n.º 14
0
func TestLists_ListOfNullableObjects_ContainsNull(t *testing.T) {
	ttype := graphql.NewList(graphql.Int)
	data := []interface{}{
		1, nil, 2,
	}
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": []interface{}{
					1, nil, 2,
				},
			},
		},
	}
	checkList(t, ttype, data, expected)
}
Exemplo n.º 15
0
// Describe [T!]! Array<T>
func TestLists_NonNullListOfNonNullObjects_ContainsValues(t *testing.T) {
	ttype := graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(graphql.Int)))
	data := []interface{}{
		1, 2,
	}
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": []interface{}{
					1, 2,
				},
			},
		},
	}
	checkList(t, ttype, data, expected)
}
Exemplo n.º 16
0
func TestLists_NullableListOfNonNullFunc_ReturnsNull(t *testing.T) {
	ttype := graphql.NewList(graphql.NewNonNull(graphql.Int))

	// `data` is a function that return values
	// Note that its uses the expected signature `func() interface{} {...}`
	data := func() interface{} {
		return nil
	}
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": nil,
			},
		},
	}
	checkList(t, ttype, data, expected)
}
Exemplo n.º 17
0
func TestLists_UserErrorExpectIterableButDidNotGetOne(t *testing.T) {
	ttype := graphql.NewList(graphql.Int)
	data := "Not an iterable"
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": nil,
			},
		},
		Errors: []gqlerrors.FormattedError{
			{
				Message:   "User Error: expected iterable, but did not find one for field DataType.test.",
				Locations: []location.SourceLocation{},
			},
		},
	}
	checkList(t, ttype, data, expected)
}
Exemplo n.º 18
0
func ConnectionDefinitions(config ConnectionConfig) *GraphQLConnectionDefinitions {

	edgeType := graphql.NewObject(graphql.ObjectConfig{
		Name:        config.Name + "Edge",
		Description: "An edge in a connection",
		Fields: graphql.Fields{
			"node": &graphql.Field{
				Type:        config.NodeType,
				Description: "The item at the end of the edge",
			},
			"cursor": &graphql.Field{
				Type:        graphql.NewNonNull(graphql.String),
				Description: " cursor for use in pagination",
			},
		},
	})
	for fieldName, fieldConfig := range config.EdgeFields {
		edgeType.AddFieldConfig(fieldName, fieldConfig)
	}

	connectionType := graphql.NewObject(graphql.ObjectConfig{
		Name:        config.Name + "Connection",
		Description: "A connection to a list of items.",

		Fields: graphql.Fields{
			"pageInfo": &graphql.Field{
				Type:        graphql.NewNonNull(pageInfoType),
				Description: "Information to aid in pagination.",
			},
			"edges": &graphql.Field{
				Type:        graphql.NewList(edgeType),
				Description: "Information to aid in pagination.",
			},
		},
	})
	for fieldName, fieldConfig := range config.ConnectionFields {
		connectionType.AddFieldConfig(fieldName, fieldConfig)
	}

	return &GraphQLConnectionDefinitions{
		EdgeType:       edgeType,
		ConnectionType: connectionType,
	}
}
Exemplo n.º 19
0
// Describe [T] Func()Array<T> // equivalent to Promise<Array<T>>
func TestLists_ListOfNullableFunc_ContainsValues(t *testing.T) {
	ttype := graphql.NewList(graphql.Int)

	// `data` is a function that return values
	// Note that its uses the expected signature `func() interface{} {...}`
	data := func() interface{} {
		return []interface{}{
			1, 2,
		}
	}
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": []interface{}{
					1, 2,
				},
			},
		},
	}
	checkList(t, ttype, data, expected)
}
Exemplo n.º 20
0
func TestExecutesUsingAComplexSchema(t *testing.T) {

	johnSmith = &testAuthor{
		Id:   123,
		Name: "John Smith",
		Pic: func(width string, height string) *testPic {
			return getPic(123, width, height)
		},
		RecentArticle: article("1"),
	}

	blogImage := graphql.NewObject(graphql.ObjectConfig{
		Name: "Image",
		Fields: graphql.Fields{
			"url": &graphql.Field{
				Type: graphql.String,
			},
			"width": &graphql.Field{
				Type: graphql.Int,
			},
			"height": &graphql.Field{
				Type: graphql.Int,
			},
		},
	})
	blogAuthor := graphql.NewObject(graphql.ObjectConfig{
		Name: "Author",
		Fields: graphql.Fields{
			"id": &graphql.Field{
				Type: graphql.String,
			},
			"name": &graphql.Field{
				Type: graphql.String,
			},
			"pic": &graphql.Field{
				Type: blogImage,
				Args: graphql.FieldConfigArgument{
					"width": &graphql.ArgumentConfig{
						Type: graphql.Int,
					},
					"height": &graphql.ArgumentConfig{
						Type: graphql.Int,
					},
				},
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					if author, ok := p.Source.(*testAuthor); ok {
						width := fmt.Sprintf("%v", p.Args["width"])
						height := fmt.Sprintf("%v", p.Args["height"])
						return author.Pic(width, height), nil
					}
					return nil, nil
				},
			},
			"recentArticle": &graphql.Field{},
		},
	})
	blogArticle := graphql.NewObject(graphql.ObjectConfig{
		Name: "Article",
		Fields: graphql.Fields{
			"id": &graphql.Field{
				Type: graphql.NewNonNull(graphql.String),
			},
			"isPublished": &graphql.Field{
				Type: graphql.Boolean,
			},
			"author": &graphql.Field{
				Type: blogAuthor,
			},
			"title": &graphql.Field{
				Type: graphql.String,
			},
			"body": &graphql.Field{
				Type: graphql.String,
			},
			"keywords": &graphql.Field{
				Type: graphql.NewList(graphql.String),
			},
		},
	})

	blogAuthor.AddFieldConfig("recentArticle", &graphql.Field{
		Type: blogArticle,
	})

	blogQuery := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"article": &graphql.Field{
				Type: blogArticle,
				Args: graphql.FieldConfigArgument{
					"id": &graphql.ArgumentConfig{
						Type: graphql.ID,
					},
				},
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					id := p.Args["id"]
					return article(id), nil
				},
			},
			"feed": &graphql.Field{
				Type: graphql.NewList(blogArticle),
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return []*testArticle{
						article(1),
						article(2),
						article(3),
						article(4),
						article(5),
						article(6),
						article(7),
						article(8),
						article(9),
						article(10),
					}, nil
				},
			},
		},
	})

	blogSchema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: blogQuery,
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

	request := `
      {
        feed {
          id,
          title
        },
        article(id: "1") {
          ...articleFields,
          author {
            id,
            name,
            pic(width: 640, height: 480) {
              url,
              width,
              height
            },
            recentArticle {
              ...articleFields,
              keywords
            }
          }
        }
      }

      fragment articleFields on Article {
        id,
        isPublished,
        title,
        body,
        hidden,
        notdefined
      }
	`

	expected := &graphql.Result{
		Data: map[string]interface{}{
			"article": map[string]interface{}{
				"title": "My Article 1",
				"body":  "This is a post",
				"author": map[string]interface{}{
					"id":   "123",
					"name": "John Smith",
					"pic": map[string]interface{}{
						"url":    "cdn://123",
						"width":  640,
						"height": 480,
					},
					"recentArticle": map[string]interface{}{
						"id":          "1",
						"isPublished": bool(true),
						"title":       "My Article 1",
						"body":        "This is a post",
						"keywords": []interface{}{
							"foo",
							"bar",
							"1",
							"true",
							nil,
						},
					},
				},
				"id":          "1",
				"isPublished": bool(true),
			},
			"feed": []interface{}{
				map[string]interface{}{
					"id":    "1",
					"title": "My Article 1",
				},
				map[string]interface{}{
					"id":    "2",
					"title": "My Article 2",
				},
				map[string]interface{}{
					"id":    "3",
					"title": "My Article 3",
				},
				map[string]interface{}{
					"id":    "4",
					"title": "My Article 4",
				},
				map[string]interface{}{
					"id":    "5",
					"title": "My Article 5",
				},
				map[string]interface{}{
					"id":    "6",
					"title": "My Article 6",
				},
				map[string]interface{}{
					"id":    "7",
					"title": "My Article 7",
				},
				map[string]interface{}{
					"id":    "8",
					"title": "My Article 8",
				},
				map[string]interface{}{
					"id":    "9",
					"title": "My Article 9",
				},
				map[string]interface{}{
					"id":    "10",
					"title": "My Article 10",
				},
			},
		},
	}

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

	// execute
	ep := graphql.ExecuteParams{
		Schema: blogSchema,
		AST:    ast,
	}
	result := testutil.TestExecute(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 init() {
	someBoxInterface = graphql.NewInterface(graphql.InterfaceConfig{
		Name: "SomeBox",
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			return stringBoxObject
		},
		Fields: graphql.FieldsThunk(func() graphql.Fields {
			return graphql.Fields{
				"deepBox": &graphql.Field{
					Type: someBoxInterface,
				},
				"unrelatedField": &graphql.Field{
					Type: graphql.String,
				},
			}
		}),
	})
	stringBoxObject = graphql.NewObject(graphql.ObjectConfig{
		Name: "StringBox",
		Interfaces: (graphql.InterfacesThunk)(func() []*graphql.Interface {
			return []*graphql.Interface{someBoxInterface}
		}),
		Fields: graphql.FieldsThunk(func() graphql.Fields {
			return graphql.Fields{
				"scalar": &graphql.Field{
					Type: graphql.String,
				},
				"deepBox": &graphql.Field{
					Type: stringBoxObject,
				},
				"unrelatedField": &graphql.Field{
					Type: graphql.String,
				},
				"listStringBox": &graphql.Field{
					Type: graphql.NewList(stringBoxObject),
				},
				"stringBox": &graphql.Field{
					Type: stringBoxObject,
				},
				"intBox": &graphql.Field{
					Type: intBoxObject,
				},
			}
		}),
	})
	intBoxObject = graphql.NewObject(graphql.ObjectConfig{
		Name: "IntBox",
		Interfaces: (graphql.InterfacesThunk)(func() []*graphql.Interface {
			return []*graphql.Interface{someBoxInterface}
		}),
		Fields: graphql.FieldsThunk(func() graphql.Fields {
			return graphql.Fields{
				"scalar": &graphql.Field{
					Type: graphql.Int,
				},
				"deepBox": &graphql.Field{
					Type: someBoxInterface,
				},
				"unrelatedField": &graphql.Field{
					Type: graphql.String,
				},
				"listStringBox": &graphql.Field{
					Type: graphql.NewList(stringBoxObject),
				},
				"stringBox": &graphql.Field{
					Type: stringBoxObject,
				},
				"intBox": &graphql.Field{
					Type: intBoxObject,
				},
			}
		}),
	})
	var nonNullStringBox1Interface = graphql.NewInterface(graphql.InterfaceConfig{
		Name: "NonNullStringBox1",
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			return stringBoxObject
		},
		Fields: graphql.Fields{
			"scalar": &graphql.Field{
				Type: graphql.NewNonNull(graphql.String),
			},
		},
	})
	NonNullStringBox1Impl := graphql.NewObject(graphql.ObjectConfig{
		Name: "NonNullStringBox1Impl",
		Interfaces: (graphql.InterfacesThunk)(func() []*graphql.Interface {
			return []*graphql.Interface{someBoxInterface, nonNullStringBox1Interface}
		}),
		Fields: graphql.Fields{
			"scalar": &graphql.Field{
				Type: graphql.NewNonNull(graphql.String),
			},
			"unrelatedField": &graphql.Field{
				Type: graphql.String,
			},
			"deepBox": &graphql.Field{
				Type: someBoxInterface,
			},
		},
	})
	var nonNullStringBox2Interface = graphql.NewInterface(graphql.InterfaceConfig{
		Name: "NonNullStringBox2",
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			return stringBoxObject
		},
		Fields: graphql.Fields{
			"scalar": &graphql.Field{
				Type: graphql.NewNonNull(graphql.String),
			},
		},
	})
	NonNullStringBox2Impl := graphql.NewObject(graphql.ObjectConfig{
		Name: "NonNullStringBox2Impl",
		Interfaces: (graphql.InterfacesThunk)(func() []*graphql.Interface {
			return []*graphql.Interface{someBoxInterface, nonNullStringBox2Interface}
		}),
		Fields: graphql.Fields{
			"scalar": &graphql.Field{
				Type: graphql.NewNonNull(graphql.String),
			},
			"unrelatedField": &graphql.Field{
				Type: graphql.String,
			},
			"deepBox": &graphql.Field{
				Type: someBoxInterface,
			},
		},
	})

	var connectionObject = graphql.NewObject(graphql.ObjectConfig{
		Name: "Connection",
		Fields: graphql.Fields{
			"edges": &graphql.Field{
				Type: graphql.NewList(graphql.NewObject(graphql.ObjectConfig{
					Name: "Edge",
					Fields: graphql.Fields{
						"node": &graphql.Field{
							Type: graphql.NewObject(graphql.ObjectConfig{
								Name: "Node",
								Fields: graphql.Fields{
									"id": &graphql.Field{
										Type: graphql.ID,
									},
									"name": &graphql.Field{
										Type: graphql.String,
									},
								},
							}),
						},
					},
				})),
			},
		},
	})
	var err error
	schema, err = graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "QueryRoot",
			Fields: graphql.Fields{
				"someBox": &graphql.Field{
					Type: someBoxInterface,
				},
				"connection": &graphql.Field{
					Type: connectionObject,
				},
			},
		}),
		Types: []graphql.Type{
			intBoxObject,
			stringBoxObject,
			NonNullStringBox1Impl,
			NonNullStringBox2Impl,
		},
	})
	if err != nil {
		panic(err)
	}
}
Exemplo n.º 22
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.Fields{
			"id": &graphql.Field{
				Type:        graphql.NewNonNull(graphql.String),
				Description: "The id of the character.",
			},
			"name": &graphql.Field{
				Type:        graphql.String,
				Description: "The name of the character.",
			},
			"appearsIn": &graphql.Field{
				Type:        graphql.NewList(episodeEnum),
				Description: "Which movies they appear in.",
			},
		},
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			if character, ok := p.Value.(StarWarsChar); ok {
				id, _ := strconv.Atoi(character.ID)
				human := GetHuman(id)
				if human.ID != "" {
					return humanType
				}
			}
			return droidType
		},
	})
	characterInterface.AddFieldConfig("friends", &graphql.Field{
		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.Fields{
			"id": &graphql.Field{
				Type:        graphql.NewNonNull(graphql.String),
				Description: "The id of the human.",
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.ID, nil
					}
					return nil, nil
				},
			},
			"name": &graphql.Field{
				Type:        graphql.String,
				Description: "The name of the human.",
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Name, nil
					}
					return nil, nil
				},
			},
			"friends": &graphql.Field{
				Type:        graphql.NewList(characterInterface),
				Description: "The friends of the human, or an empty list if they have none.",
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Friends, nil
					}
					return []interface{}{}, nil
				},
			},
			"appearsIn": &graphql.Field{
				Type:        graphql.NewList(episodeEnum),
				Description: "Which movies they appear in.",
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.AppearsIn, nil
					}
					return nil, nil
				},
			},
			"homePlanet": &graphql.Field{
				Type:        graphql.String,
				Description: "The home planet of the human, or null if unknown.",
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.HomePlanet, nil
					}
					return nil, nil
				},
			},
		},
		Interfaces: []*graphql.Interface{
			characterInterface,
		},
	})
	droidType = graphql.NewObject(graphql.ObjectConfig{
		Name:        "Droid",
		Description: "A mechanical creature in the Star Wars universe.",
		Fields: graphql.Fields{
			"id": &graphql.Field{
				Type:        graphql.NewNonNull(graphql.String),
				Description: "The id of the droid.",
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.ID, nil
					}
					return nil, nil
				},
			},
			"name": &graphql.Field{
				Type:        graphql.String,
				Description: "The name of the droid.",
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.Name, nil
					}
					return nil, nil
				},
			},
			"friends": &graphql.Field{
				Type:        graphql.NewList(characterInterface),
				Description: "The friends of the droid, or an empty list if they have none.",
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					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, nil
					}
					return []interface{}{}, nil
				},
			},
			"appearsIn": &graphql.Field{
				Type:        graphql.NewList(episodeEnum),
				Description: "Which movies they appear in.",
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.AppearsIn, nil
					}
					return nil, nil
				},
			},
			"primaryFunction": &graphql.Field{
				Type:        graphql.String,
				Description: "The primary function of the droid.",
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.PrimaryFunction, nil
					}
					return nil, nil
				},
			},
		},
		Interfaces: []*graphql.Interface{
			characterInterface,
		},
	})

	queryType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"hero": &graphql.Field{
				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.ResolveParams) (interface{}, error) {
					return GetHero(p.Args["episode"]), nil
				},
			},
			"human": &graphql.Field{
				Type: humanType,
				Args: graphql.FieldConfigArgument{
					"id": &graphql.ArgumentConfig{
						Description: "id of the human",
						Type:        graphql.NewNonNull(graphql.String),
					},
				},
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return GetHuman(p.Args["id"].(int)), nil
				},
			},
			"droid": &graphql.Field{
				Type: droidType,
				Args: graphql.FieldConfigArgument{
					"id": &graphql.ArgumentConfig{
						Description: "id of the droid",
						Type:        graphql.NewNonNull(graphql.String),
					},
				},
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return GetDroid(p.Args["id"].(int)), nil
				},
			},
		},
	})
	StarWarsSchema, _ = graphql.NewSchema(graphql.SchemaConfig{
		Query: queryType,
	})
}
Exemplo n.º 23
0
func init() {

	var beingInterface = graphql.NewInterface(graphql.InterfaceConfig{
		Name: "Being",
		Fields: graphql.Fields{
			"name": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"surname": &graphql.ArgumentConfig{
						Type: graphql.Boolean,
					},
				},
			},
		},
	})
	var petInterface = graphql.NewInterface(graphql.InterfaceConfig{
		Name: "Pet",
		Fields: graphql.Fields{
			"name": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"surname": &graphql.ArgumentConfig{
						Type: graphql.Boolean,
					},
				},
			},
		},
	})
	var canineInterface = graphql.NewInterface(graphql.InterfaceConfig{
		Name: "Canine",
		Fields: graphql.Fields{
			"name": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"surname": &graphql.ArgumentConfig{
						Type: graphql.Boolean,
					},
				},
			},
		},
	})
	var dogCommandEnum = graphql.NewEnum(graphql.EnumConfig{
		Name: "DogCommand",
		Values: graphql.EnumValueConfigMap{
			"SIT": &graphql.EnumValueConfig{
				Value: 0,
			},
			"HEEL": &graphql.EnumValueConfig{
				Value: 1,
			},
			"DOWN": &graphql.EnumValueConfig{
				Value: 2,
			},
		},
	})
	var dogType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Dog",
		IsTypeOf: func(p graphql.IsTypeOfParams) bool {
			return true
		},
		Fields: graphql.Fields{
			"name": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"surname": &graphql.ArgumentConfig{
						Type: graphql.Boolean,
					},
				},
			},
			"nickname": &graphql.Field{
				Type: graphql.String,
			},
			"barkVolume": &graphql.Field{
				Type: graphql.Int,
			},
			"barks": &graphql.Field{
				Type: graphql.Boolean,
			},
			"doesKnowCommand": &graphql.Field{
				Type: graphql.Boolean,
				Args: graphql.FieldConfigArgument{
					"dogCommand": &graphql.ArgumentConfig{
						Type: dogCommandEnum,
					},
				},
			},
			"isHousetrained": &graphql.Field{
				Type: graphql.Boolean,
				Args: graphql.FieldConfigArgument{
					"atOtherHomes": &graphql.ArgumentConfig{
						Type:         graphql.Boolean,
						DefaultValue: true,
					},
				},
			},
			"isAtLocation": &graphql.Field{
				Type: graphql.Boolean,
				Args: graphql.FieldConfigArgument{
					"x": &graphql.ArgumentConfig{
						Type: graphql.Int,
					},
					"y": &graphql.ArgumentConfig{
						Type: graphql.Int,
					},
				},
			},
		},
		Interfaces: []*graphql.Interface{
			beingInterface,
			petInterface,
			canineInterface,
		},
	})
	var furColorEnum = graphql.NewEnum(graphql.EnumConfig{
		Name: "FurColor",
		Values: graphql.EnumValueConfigMap{
			"BROWN": &graphql.EnumValueConfig{
				Value: 0,
			},
			"BLACK": &graphql.EnumValueConfig{
				Value: 1,
			},
			"TAN": &graphql.EnumValueConfig{
				Value: 2,
			},
			"SPOTTED": &graphql.EnumValueConfig{
				Value: 3,
			},
		},
	})

	var catType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Cat",
		IsTypeOf: func(p graphql.IsTypeOfParams) bool {
			return true
		},
		Fields: graphql.Fields{
			"name": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"surname": &graphql.ArgumentConfig{
						Type: graphql.Boolean,
					},
				},
			},
			"nickname": &graphql.Field{
				Type: graphql.String,
			},
			"meowVolume": &graphql.Field{
				Type: graphql.Int,
			},
			"meows": &graphql.Field{
				Type: graphql.Boolean,
			},
			"furColor": &graphql.Field{
				Type: furColorEnum,
			},
		},
		Interfaces: []*graphql.Interface{
			beingInterface,
			petInterface,
		},
	})
	var catOrDogUnion = graphql.NewUnion(graphql.UnionConfig{
		Name: "CatOrDog",
		Types: []*graphql.Object{
			dogType,
			catType,
		},
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			// not used for validation
			return nil
		},
	})
	var intelligentInterface = graphql.NewInterface(graphql.InterfaceConfig{
		Name: "Intelligent",
		Fields: graphql.Fields{
			"iq": &graphql.Field{
				Type: graphql.Int,
			},
		},
	})

	var humanType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Human",
		IsTypeOf: func(p graphql.IsTypeOfParams) bool {
			return true
		},
		Interfaces: []*graphql.Interface{
			beingInterface,
			intelligentInterface,
		},
		Fields: graphql.Fields{
			"name": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"surname": &graphql.ArgumentConfig{
						Type: graphql.Boolean,
					},
				},
			},
			"pets": &graphql.Field{
				Type: graphql.NewList(petInterface),
			},
			"iq": &graphql.Field{
				Type: graphql.Int,
			},
		},
	})

	humanType.AddFieldConfig("relatives", &graphql.Field{
		Type: graphql.NewList(humanType),
	})

	var alienType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Alien",
		IsTypeOf: func(p graphql.IsTypeOfParams) bool {
			return true
		},
		Interfaces: []*graphql.Interface{
			beingInterface,
			intelligentInterface,
		},
		Fields: graphql.Fields{
			"name": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"surname": &graphql.ArgumentConfig{
						Type: graphql.Boolean,
					},
				},
			},
			"iq": &graphql.Field{
				Type: graphql.Int,
			},
			"numEyes": &graphql.Field{
				Type: graphql.Int,
			},
		},
	})
	var dogOrHumanUnion = graphql.NewUnion(graphql.UnionConfig{
		Name: "DogOrHuman",
		Types: []*graphql.Object{
			dogType,
			humanType,
		},
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			// not used for validation
			return nil
		},
	})
	var humanOrAlienUnion = graphql.NewUnion(graphql.UnionConfig{
		Name: "HumanOrAlien",
		Types: []*graphql.Object{
			alienType,
			humanType,
		},
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			// not used for validation
			return nil
		},
	})

	var complexInputObject = graphql.NewInputObject(graphql.InputObjectConfig{
		Name: "ComplexInput",
		Fields: graphql.InputObjectConfigFieldMap{
			"requiredField": &graphql.InputObjectFieldConfig{
				Type: graphql.NewNonNull(graphql.Boolean),
			},
			"intField": &graphql.InputObjectFieldConfig{
				Type: graphql.Int,
			},
			"stringField": &graphql.InputObjectFieldConfig{
				Type: graphql.String,
			},
			"booleanField": &graphql.InputObjectFieldConfig{
				Type: graphql.Boolean,
			},
			"stringListField": &graphql.InputObjectFieldConfig{
				Type: graphql.NewList(graphql.String),
			},
		},
	})
	var complicatedArgs = graphql.NewObject(graphql.ObjectConfig{
		Name: "ComplicatedArgs",
		// TODO List
		// TODO Coercion
		// TODO NotNulls
		Fields: graphql.Fields{
			"intArgField": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"intArg": &graphql.ArgumentConfig{
						Type: graphql.Int,
					},
				},
			},
			"nonNullIntArgField": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"nonNullIntArg": &graphql.ArgumentConfig{
						Type: graphql.NewNonNull(graphql.Int),
					},
				},
			},
			"stringArgField": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"stringArg": &graphql.ArgumentConfig{
						Type: graphql.String,
					},
				},
			},
			"booleanArgField": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"booleanArg": &graphql.ArgumentConfig{
						Type: graphql.Boolean,
					},
				},
			},
			"enumArgField": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"enumArg": &graphql.ArgumentConfig{
						Type: furColorEnum,
					},
				},
			},
			"floatArgField": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"floatArg": &graphql.ArgumentConfig{
						Type: graphql.Float,
					},
				},
			},
			"idArgField": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"idArg": &graphql.ArgumentConfig{
						Type: graphql.ID,
					},
				},
			},
			"stringListArgField": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"stringListArg": &graphql.ArgumentConfig{
						Type: graphql.NewList(graphql.String),
					},
				},
			},
			"complexArgField": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"complexArg": &graphql.ArgumentConfig{
						Type: complexInputObject,
					},
				},
			},
			"multipleReqs": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"req1": &graphql.ArgumentConfig{
						Type: graphql.NewNonNull(graphql.Int),
					},
					"req2": &graphql.ArgumentConfig{
						Type: graphql.NewNonNull(graphql.Int),
					},
				},
			},
			"multipleOpts": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"opt1": &graphql.ArgumentConfig{
						Type:         graphql.Int,
						DefaultValue: 0,
					},
					"opt2": &graphql.ArgumentConfig{
						Type:         graphql.Int,
						DefaultValue: 0,
					},
				},
			},
			"multipleOptAndReq": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"req1": &graphql.ArgumentConfig{
						Type: graphql.NewNonNull(graphql.Int),
					},
					"req2": &graphql.ArgumentConfig{
						Type: graphql.NewNonNull(graphql.Int),
					},
					"opt1": &graphql.ArgumentConfig{
						Type:         graphql.Int,
						DefaultValue: 0,
					},
					"opt2": &graphql.ArgumentConfig{
						Type:         graphql.Int,
						DefaultValue: 0,
					},
				},
			},
		},
	})
	queryRoot := graphql.NewObject(graphql.ObjectConfig{
		Name: "QueryRoot",
		Fields: graphql.Fields{
			"human": &graphql.Field{
				Args: graphql.FieldConfigArgument{
					"id": &graphql.ArgumentConfig{
						Type: graphql.ID,
					},
				},
				Type: humanType,
			},
			"alien": &graphql.Field{
				Type: alienType,
			},
			"dog": &graphql.Field{
				Type: dogType,
			},
			"cat": &graphql.Field{
				Type: catType,
			},
			"pet": &graphql.Field{
				Type: petInterface,
			},
			"catOrDog": &graphql.Field{
				Type: catOrDogUnion,
			},
			"dogOrHuman": &graphql.Field{
				Type: dogOrHumanUnion,
			},
			"humanOrAlien": &graphql.Field{
				Type: humanOrAlienUnion,
			},
			"complicatedArgs": &graphql.Field{
				Type: complicatedArgs,
			},
		},
	})
	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: queryRoot,
		Directives: []*graphql.Directive{
			graphql.NewDirective(graphql.DirectiveConfig{
				Name:      "operationOnly",
				Locations: []string{graphql.DirectiveLocationQuery},
			}),
			graphql.IncludeDirective,
			graphql.SkipDirective,
		},
		Types: []graphql.Type{
			catType,
			dogType,
			humanType,
			alienType,
		},
	})
	if err != nil {
		panic(err)
	}
	TestSchema = &schema

}
Exemplo n.º 24
0
func TestIntrospection_ExecutesAnInputObject(t *testing.T) {

	testInputObject := graphql.NewInputObject(graphql.InputObjectConfig{
		Name: "TestInputObject",
		Fields: graphql.InputObjectConfigFieldMap{
			"a": &graphql.InputObjectFieldConfig{
				Type:         graphql.String,
				DefaultValue: "foo",
			},
			"b": &graphql.InputObjectFieldConfig{
				Type: graphql.NewList(graphql.String),
			},
		},
	})
	testType := graphql.NewObject(graphql.ObjectConfig{
		Name: "TestType",
		Fields: graphql.Fields{
			"field": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"complex": &graphql.ArgumentConfig{
						Type: testInputObject,
					},
				},
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return p.Args["complex"], nil
				},
			},
		},
	})
	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: testType,
	})
	if err != nil {
		t.Fatalf("Error creating Schema: %v", err.Error())
	}
	query := `
      {
        __schema {
          types {
            kind
            name
            inputFields {
              name
              type { ...TypeRef }
              defaultValue
            }
          }
        }
      }

      fragment TypeRef on __Type {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
            }
          }
        }
      }
    `
	expectedDataSubSet := map[string]interface{}{
		"__schema": map[string]interface{}{
			"types": []interface{}{
				map[string]interface{}{
					"kind": "INPUT_OBJECT",
					"name": "TestInputObject",
					"inputFields": []interface{}{
						map[string]interface{}{
							"name": "a",
							"type": map[string]interface{}{
								"kind":   "SCALAR",
								"name":   "String",
								"ofType": nil,
							},
							"defaultValue": `"foo"`,
						},
						map[string]interface{}{
							"name": "b",
							"type": map[string]interface{}{
								"kind": "LIST",
								"name": nil,
								"ofType": map[string]interface{}{
									"kind":   "SCALAR",
									"name":   "String",
									"ofType": nil,
								},
							},
							"defaultValue": nil,
						},
					},
				},
			},
		},
	}

	result := g(t, graphql.Params{
		Schema:        schema,
		RequestString: query,
	})
	if !testutil.ContainSubset(result.Data.(map[string]interface{}), expectedDataSubSet) {
		t.Fatalf("unexpected, result does not contain subset of expected data")
	}
}
Exemplo n.º 25
0
func TestFailsWhenAnIsTypeOfCheckIsNotMet(t *testing.T) {

	query := `{ specials { value } }`

	data := map[string]interface{}{
		"specials": []interface{}{
			testSpecialType{"foo"},
			testNotSpecialType{"bar"},
		},
	}

	expected := &graphql.Result{
		Data: map[string]interface{}{
			"specials": []interface{}{
				map[string]interface{}{
					"value": "foo",
				},
				nil,
			},
		},
		Errors: []gqlerrors.FormattedError{
			{
				Message:   `Expected value of type "SpecialType" but got: graphql_test.testNotSpecialType.`,
				Locations: []location.SourceLocation{},
			},
		},
	}

	specialType := graphql.NewObject(graphql.ObjectConfig{
		Name: "SpecialType",
		IsTypeOf: func(p graphql.IsTypeOfParams) bool {
			if _, ok := p.Value.(testSpecialType); ok {
				return true
			}
			return false
		},
		Fields: graphql.Fields{
			"value": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return p.Source.(testSpecialType).Value, nil
				},
			},
		},
	})
	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "Query",
			Fields: graphql.Fields{
				"specials": &graphql.Field{
					Type: graphql.NewList(specialType),
					Resolve: func(p graphql.ResolveParams) (interface{}, error) {
						return p.Source.(map[string]interface{})["specials"], nil
					},
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

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

	// execute
	ep := graphql.ExecuteParams{
		Schema: schema,
		AST:    ast,
		Root:   data,
	}
	result := testutil.TestExecute(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))
	}
}
Exemplo n.º 26
0
func TestUnionIntersectionTypes_GetsExecutionInfoInResolver(t *testing.T) {

	var encounteredContextValue string
	var encounteredSchema graphql.Schema
	var encounteredRootValue string
	var personType2 *graphql.Object

	namedType2 := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "Named",
		Fields: graphql.Fields{
			"name": &graphql.Field{
				Type: graphql.String,
			},
		},
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			encounteredSchema = p.Info.Schema
			encounteredContextValue, _ = p.Context.Value("authToken").(string)
			encounteredRootValue = p.Info.RootValue.(*testPerson).Name
			return personType2
		},
	})

	personType2 = graphql.NewObject(graphql.ObjectConfig{
		Name: "Person",
		Interfaces: []*graphql.Interface{
			namedType2,
		},
		Fields: graphql.Fields{
			"name": &graphql.Field{
				Type: graphql.String,
			},
			"friends": &graphql.Field{
				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)

	// create context
	ctx := context.Background()
	ctx = context.WithValue(ctx, "authToken", "contextStringValue123")

	// execute
	ep := graphql.ExecuteParams{
		Schema:  schema2,
		AST:     ast,
		Root:    john2,
		Context: ctx,
	}
	result := testutil.TestExecute(t, ep)

	if !reflect.DeepEqual(expected, result) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
	}
	if !reflect.DeepEqual("contextStringValue123", encounteredContextValue) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff("contextStringValue123", encounteredContextValue))
	}
	if !reflect.DeepEqual("John", encounteredRootValue) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff("John", encounteredRootValue))
	}
	if !reflect.DeepEqual(schema2, encounteredSchema) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(schema2, encounteredSchema))
	}
}
Exemplo n.º 27
0
		astValue := valueAST.GetValue()
		if astValue, ok := astValue.(string); ok && astValue == "SerializedValue" {
			return "DeserializedValue"
		}
		return nil
	},
})

var testInputObject *graphql.InputObject = graphql.NewInputObject(graphql.InputObjectConfig{
	Name: "TestInputObject",
	Fields: graphql.InputObjectConfigFieldMap{
		"a": &graphql.InputObjectFieldConfig{
			Type: graphql.String,
		},
		"b": &graphql.InputObjectFieldConfig{
			Type: graphql.NewList(graphql.String),
		},
		"c": &graphql.InputObjectFieldConfig{
			Type: graphql.NewNonNull(graphql.String),
		},
		"d": &graphql.InputObjectFieldConfig{
			Type: testComplexScalar,
		},
	},
})

var testNestedInputObject *graphql.InputObject = graphql.NewInputObject(graphql.InputObjectConfig{
	Name: "TestNestedInputObject",
	Fields: graphql.InputObjectConfigFieldMap{
		"na": &graphql.InputObjectFieldConfig{
			Type: graphql.NewNonNull(testInputObject),
Exemplo n.º 28
0
func TestExecutesArbitraryCode(t *testing.T) {

	deepData := map[string]interface{}{}
	data := map[string]interface{}{
		"a": func() interface{} { return "Apple" },
		"b": func() interface{} { return "Banana" },
		"c": func() interface{} { return "Cookie" },
		"d": func() interface{} { return "Donut" },
		"e": func() interface{} { return "Egg" },
		"f": "Fish",
		"pic": func(size int) string {
			return fmt.Sprintf("Pic of size: %v", size)
		},
		"deep": func() interface{} { return deepData },
	}
	data["promise"] = func() interface{} {
		return data
	}
	deepData = map[string]interface{}{
		"a":      func() interface{} { return "Already Been Done" },
		"b":      func() interface{} { return "Boring" },
		"c":      func() interface{} { return []string{"Contrived", "", "Confusing"} },
		"deeper": func() interface{} { return []interface{}{data, nil, data} },
	}

	query := `
      query Example($size: Int) {
        a,
        b,
        x: c
        ...c
        f
        ...on DataType {
          pic(size: $size)
          promise {
            a
          }
        }
        deep {
          a
          b
          c
          deeper {
            a
            b
          }
        }
      }

      fragment c on DataType {
        d
        e
      }
    `

	expected := &graphql.Result{
		Data: map[string]interface{}{
			"b": "Banana",
			"x": "Cookie",
			"d": "Donut",
			"e": "Egg",
			"promise": map[string]interface{}{
				"a": "Apple",
			},
			"a": "Apple",
			"deep": map[string]interface{}{
				"a": "Already Been Done",
				"b": "Boring",
				"c": []interface{}{
					"Contrived",
					nil,
					"Confusing",
				},
				"deeper": []interface{}{
					map[string]interface{}{
						"a": "Apple",
						"b": "Banana",
					},
					nil,
					map[string]interface{}{
						"a": "Apple",
						"b": "Banana",
					},
				},
			},
			"f":   "Fish",
			"pic": "Pic of size: 100",
		},
	}

	// Schema Definitions
	picResolverFn := func(p graphql.ResolveParams) (interface{}, error) {
		// get and type assert ResolveFn for this field
		picResolver, ok := p.Source.(map[string]interface{})["pic"].(func(size int) string)
		if !ok {
			return nil, nil
		}
		// get and type assert argument
		sizeArg, ok := p.Args["size"].(int)
		if !ok {
			return nil, nil
		}
		return picResolver(sizeArg), nil
	}
	dataType := graphql.NewObject(graphql.ObjectConfig{
		Name: "DataType",
		Fields: graphql.Fields{
			"a": &graphql.Field{
				Type: graphql.String,
			},
			"b": &graphql.Field{
				Type: graphql.String,
			},
			"c": &graphql.Field{
				Type: graphql.String,
			},
			"d": &graphql.Field{
				Type: graphql.String,
			},
			"e": &graphql.Field{
				Type: graphql.String,
			},
			"f": &graphql.Field{
				Type: graphql.String,
			},
			"pic": &graphql.Field{
				Args: graphql.FieldConfigArgument{
					"size": &graphql.ArgumentConfig{
						Type: graphql.Int,
					},
				},
				Type:    graphql.String,
				Resolve: picResolverFn,
			},
		},
	})
	deepDataType := graphql.NewObject(graphql.ObjectConfig{
		Name: "DeepDataType",
		Fields: graphql.Fields{
			"a": &graphql.Field{
				Type: graphql.String,
			},
			"b": &graphql.Field{
				Type: graphql.String,
			},
			"c": &graphql.Field{
				Type: graphql.NewList(graphql.String),
			},
			"deeper": &graphql.Field{
				Type: graphql.NewList(dataType),
			},
		},
	})

	// Exploring a way to have a Object within itself
	// in this case DataType has DeepDataType has DataType
	dataType.AddFieldConfig("deep", &graphql.Field{
		Type: deepDataType,
	})
	// in this case DataType has DataType
	dataType.AddFieldConfig("promise", &graphql.Field{
		Type: dataType,
	})

	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: dataType,
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

	// parse query
	astDoc := testutil.TestParse(t, query)

	// execute
	args := map[string]interface{}{
		"size": 100,
	}
	operationName := "Example"
	ep := graphql.ExecuteParams{
		Schema:        schema,
		Root:          data,
		AST:           astDoc,
		OperationName: operationName,
		Args:          args,
	}
	result := testutil.TestExecute(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))
	}
}
Exemplo n.º 29
0
		switch value.(type) {
		case *user:
			return globalIDTestUserType
		case *photo2:
			return globalIDTestPhotoType
		default:
			panic(fmt.Sprintf("Unknown object type `%v`", value))
		}
	},
})
var globalIDTestQueryType = graphql.NewObject(graphql.ObjectConfig{
	Name: "Query",
	Fields: graphql.Fields{
		"node": globalIDTestDef.NodeField,
		"allObjects": &graphql.Field{
			Type: graphql.NewList(globalIDTestDef.NodeInterface),
			Resolve: func(p graphql.ResolveParams) (interface{}, error) {
				return []interface{}{
					globalIDTestUserData["1"],
					globalIDTestUserData["2"],
					globalIDTestPhotoData["1"],
					globalIDTestPhotoData["2"],
				}, nil
			},
		},
	},
})

// becareful not to define schema here, since globalIDTestUserType and globalIDTestPhotoType wouldn't be defined till init()
var globalIDTestSchema graphql.Schema
Exemplo n.º 30
0
			},
		},

		"lastTodo": &graphql.Field{
			Type:        todoType,
			Description: "Last todo added",
			Resolve: func(params graphql.ResolveParams) (interface{}, error) {
				return TodoList[len(TodoList)-1], nil
			},
		},

		/*
		   curl -g 'http://localhost:8080/graphql?query={todoList{id,text,done}}'
		*/
		"todoList": &graphql.Field{
			Type:        graphql.NewList(todoType),
			Description: "List of todos",
			Resolve: func(p graphql.ResolveParams) (interface{}, error) {
				return TodoList, nil
			},
		},
	},
})

// define schema, with our rootQuery and rootMutation
var schema, _ = graphql.NewSchema(graphql.SchemaConfig{
	Query:    rootQuery,
	Mutation: rootMutation,
})

func executeQuery(query string, schema graphql.Schema) *graphql.Result {