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,
	})
}
Example #2
0
func PluralIdentifyingRootField(config PluralIdentifyingRootFieldConfig) *types.GraphQLFieldConfig {
	inputArgs := types.GraphQLFieldConfigArgumentMap{}
	if config.ArgName != "" {
		inputArgs[config.ArgName] = &types.GraphQLArgumentConfig{
			Type: types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(config.InputType))),
		}
	}

	return &types.GraphQLFieldConfig{
		Description: config.Description,
		Type:        types.NewGraphQLList(config.OutputType),
		Args:        inputArgs,
		Resolve: func(p types.GQLFRParams) interface{} {
			inputs, ok := p.Args[config.ArgName]
			if !ok {
				return nil
			}

			if config.ResolveSingleInput == nil {
				return nil
			}
			switch inputs := inputs.(type) {
			case []interface{}:
				res := []interface{}{}
				for _, input := range inputs {
					r := config.ResolveSingleInput(input)
					res = append(res, r)
				}
				return res
			}
			return nil
		},
	}
}
Example #3
0
func TestLists_NonNullListOfNonNullFunc_ReturnsNull(t *testing.T) {
	ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)))

	// `data` is a function that return values
	// Note that its uses the expected signature `func() interface{} {...}`
	data := func() interface{} {
		return nil
	}
	expected := &types.GraphQLResult{
		Data: map[string]interface{}{
			"nest": nil,
		},
		Errors: []graphqlerrors.GraphQLFormattedError{
			graphqlerrors.GraphQLFormattedError{
				Message: "Cannot return null for non-nullable field DataType.test.",
				Locations: []location.SourceLocation{
					location.SourceLocation{
						Line:   1,
						Column: 10,
					},
				},
			},
		},
	}
	checkList(t, ttype, data, expected)
}
Example #4
0
func TestLists_NonNullListOfNonNullArrayOfFunc_ContainsNulls(t *testing.T) {
	ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)))

	// `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 := &types.GraphQLResult{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": []interface{}{
					1, nil, 2,
				},
			},
		},
	}
	checkList(t, ttype, data, expected)
}
func TestTypeSystem_DefinitionExample_ProhibitsNestingNonNullInsideNonNull(t *testing.T) {
	ttype := types.NewGraphQLNonNull(types.NewGraphQLNonNull(types.GraphQLInt))
	expected := `Can only create NonNull of a Nullable GraphQLType but got: Int!.`
	if ttype.GetError().Error() != expected {
		t.Fatalf(`expected %v , got: %v`, expected, ttype.GetError())
	}
}
func TestTypeSystem_DefinitionExample_StringifiesSimpleTypes(t *testing.T) {

	type Test struct {
		ttype    types.GraphQLType
		expected string
	}
	tests := []Test{
		Test{types.GraphQLInt, "Int"},
		Test{blogArticle, "Article"},
		Test{interfaceType, "Interface"},
		Test{unionType, "Union"},
		Test{enumType, "Enum"},
		Test{inputObjectType, "InputObject"},
		Test{types.NewGraphQLNonNull(types.GraphQLInt), "Int!"},
		Test{types.NewGraphQLList(types.GraphQLInt), "[Int]"},
		Test{types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLInt)), "[Int]!"},
		Test{types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)), "[Int!]"},
		Test{types.NewGraphQLList(types.NewGraphQLList(types.GraphQLInt)), "[[Int]]"},
	}
	for _, test := range tests {
		ttypeStr := fmt.Sprintf("%v", test.ttype)
		if ttypeStr != test.expected {
			t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr)
		}
	}
}
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWithAnEquivalentlyModifiedInterfaceField(t *testing.T) {
	anotherInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{
		Name: "AnotherInterface",
		ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType {
			return nil
		},
		Fields: types.GraphQLFieldConfigMap{
			"field": &types.GraphQLFieldConfig{
				Type: types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLString)),
			},
		},
	})
	anotherObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:       "AnotherObject",
		Interfaces: []*types.GraphQLInterfaceType{anotherInterface},
		Fields: types.GraphQLFieldConfigMap{
			"field": &types.GraphQLFieldConfig{
				Type: types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLString)),
			},
		},
	})
	_, err := schemaWithObjectFieldOfType(anotherObject)
	if err != nil {
		t.Fatalf(`unexpected error: %v for type "%v"`, err, anotherObject)
	}
}
func withModifiers(ttypes []types.GraphQLType) []types.GraphQLType {
	res := ttypes
	for _, ttype := range ttypes {
		res = append(res, types.NewGraphQLList(ttype))
	}
	for _, ttype := range ttypes {
		res = append(res, types.NewGraphQLNonNull(ttype))
	}
	for _, ttype := range ttypes {
		res = append(res, types.NewGraphQLNonNull(types.NewGraphQLList(ttype)))
	}
	return res
}
Example #9
0
func MutationWithClientMutationId(config MutationConfig) *types.GraphQLFieldConfig {

	augmentedInputFields := config.InputFields
	if augmentedInputFields == nil {
		augmentedInputFields = types.InputObjectConfigFieldMap{}
	}
	augmentedInputFields["clientMutationId"] = &types.InputObjectFieldConfig{
		Type: types.NewGraphQLNonNull(types.GraphQLString),
	}
	augmentedOutputFields := config.OutputFields
	if augmentedOutputFields == nil {
		augmentedOutputFields = types.GraphQLFieldConfigMap{}
	}
	augmentedOutputFields["clientMutationId"] = &types.GraphQLFieldConfig{
		Type: types.NewGraphQLNonNull(types.GraphQLString),
	}

	inputType := types.NewGraphQLInputObjectType(types.InputObjectConfig{
		Name:   config.Name + "Input",
		Fields: augmentedInputFields,
	})
	outputType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:   config.Name + "Payload",
		Fields: augmentedOutputFields,
	})
	return &types.GraphQLFieldConfig{
		Type: outputType,
		Args: types.GraphQLFieldConfigArgumentMap{
			"input": &types.GraphQLArgumentConfig{
				Type: types.NewGraphQLNonNull(inputType),
			},
		},
		Resolve: func(p types.GQLFRParams) interface{} {
			if config.MutateAndGetPayload == nil {
				return nil
			}
			input := map[string]interface{}{}
			if inputVal, ok := p.Args["input"]; ok {
				if inputVal, ok := inputVal.(map[string]interface{}); ok {
					input = inputVal
				}
			}
			payload := config.MutateAndGetPayload(input, p.Info)
			if clientMutationId, ok := input["clientMutationId"]; ok {
				payload["clientMutationId"] = clientMutationId
			}
			return payload
		},
	}
}
Example #10
0
/*
Creates the configuration for an id field on a node, using `toGlobalId` to
construct the ID from the provided typename. The type-specific ID is fetcher
by calling idFetcher on the object, or if not provided, by accessing the `id`
property on the object.
*/
func GlobalIdField(typeName string, idFetcher GlobalIdFetcherFn) *types.GraphQLFieldConfig {
	return &types.GraphQLFieldConfig{
		Name:        "id",
		Description: "The ID of an object",
		Type:        types.NewGraphQLNonNull(types.GraphQLID),
		Resolve: func(p types.GQLFRParams) interface{} {
			id := ""
			if idFetcher != nil {
				fetched := idFetcher(p.Source, p.Info)
				id = fmt.Sprintf("%v", fetched)
			} else {
				// try to get from p.Source (data)
				var objMap interface{}
				b, _ := json.Marshal(p.Source)
				_ = json.Unmarshal(b, &objMap)
				switch obj := objMap.(type) {
				case map[string]interface{}:
					if iid, ok := obj["id"]; ok {
						id = fmt.Sprintf("%v", iid)
					}
				}
			}
			globalId := ToGlobalId(typeName, id)
			return globalId
		},
	}
}
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWithADifferentlyModifiedInterfaceFieldType(t *testing.T) {
	anotherInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{
		Name: "AnotherInterface",
		ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType {
			return nil
		},
		Fields: types.GraphQLFieldConfigMap{
			"field": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	anotherObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:       "AnotherObject",
		Interfaces: []*types.GraphQLInterfaceType{anotherInterface},
		Fields: types.GraphQLFieldConfigMap{
			"field": &types.GraphQLFieldConfig{
				Type: types.NewGraphQLNonNull(types.GraphQLString),
			},
		},
	})
	_, 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)
	}
}
Example #12
0
func TestLists_NullableListOfNonNullObjects_ContainsNull(t *testing.T) {
	ttype := types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt))
	data := []interface{}{
		1, nil, 2,
	}
	expected := &types.GraphQLResult{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": nil,
			},
		},
		Errors: []graphqlerrors.GraphQLFormattedError{
			graphqlerrors.GraphQLFormattedError{
				Message: "Cannot return null for non-nullable field DataType.test.",
				Locations: []location.SourceLocation{
					location.SourceLocation{
						Line:   1,
						Column: 10,
					},
				},
			},
		},
	}
	checkList(t, ttype, data, expected)
}
func TestTypeSystem_NonNullMustAcceptGraphQLTypes_RejectsNilAsNonNullableType(t *testing.T) {
	result := types.NewGraphQLNonNull(nil)
	expectedError := `Can only create NonNull of a Nullable GraphQLType but got: <nil>.`
	if result.GetError() == nil || result.GetError().Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, result.GetError())
	}
}
func TestTypeSystem_DefinitionExample_IdentifiesOutputTypes(t *testing.T) {
	type Test struct {
		ttype    types.GraphQLType
		expected bool
	}
	tests := []Test{
		Test{types.GraphQLInt, true},
		Test{objectType, true},
		Test{interfaceType, true},
		Test{unionType, true},
		Test{enumType, true},
		Test{inputObjectType, false},
	}
	for _, test := range tests {
		ttypeStr := fmt.Sprintf("%v", test.ttype)
		if types.IsOutputType(test.ttype) != test.expected {
			t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr)
		}
		if types.IsOutputType(types.NewGraphQLList(test.ttype)) != test.expected {
			t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr)
		}
		if types.IsOutputType(types.NewGraphQLNonNull(test.ttype)) != test.expected {
			t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr)
		}
	}
}
Example #15
0
// Describe [T!]! Array<T>
func TestLists_NonNullListOfNonNullObjects_ContainsValues(t *testing.T) {
	ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)))
	data := []interface{}{
		1, 2,
	}
	expected := &types.GraphQLResult{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": []interface{}{
					1, 2,
				},
			},
		},
	}
	checkList(t, ttype, data, expected)
}
Example #16
0
func ConnectionDefinitions(config ConnectionConfig) *GraphQLConnectionDefinitions {

	edgeType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:        config.Name + "Edge",
		Description: "An edge in a connection",
		Fields: types.GraphQLFieldConfigMap{
			"node": &types.GraphQLFieldConfig{
				Type:        config.NodeType,
				Description: "The item at the end of the edge",
			},
			"cursor": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLNonNull(types.GraphQLString),
				Description: " cursor for use in pagination",
			},
		},
	})
	for fieldName, fieldConfig := range config.EdgeFields {
		edgeType.AddFieldConfig(fieldName, fieldConfig)
	}

	connectionType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:        config.Name + "Connection",
		Description: "A connection to a list of items.",

		Fields: types.GraphQLFieldConfigMap{
			"pageInfo": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLNonNull(pageInfoType),
				Description: "Information to aid in pagination.",
			},
			"edges": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(edgeType),
				Description: "Information to aid in pagination.",
			},
		},
	})
	for fieldName, fieldConfig := range config.ConnectionFields {
		connectionType.AddFieldConfig(fieldName, fieldConfig)
	}

	return &GraphQLConnectionDefinitions{
		EdgeType:       edgeType,
		ConnectionType: connectionType,
	}
}
func TestTypeSystem_NonNullMustAcceptGraphQLTypes_AcceptsAnTypeAsNullableTypeOfNonNull(t *testing.T) {
	nullableTypes := []types.GraphQLType{
		types.GraphQLString,
		someScalarType,
		someObjectType,
		someUnionType,
		someInterfaceType,
		someEnumType,
		someInputObject,
		types.NewGraphQLList(types.GraphQLString),
		types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLString)),
	}
	for _, ttype := range nullableTypes {
		result := types.NewGraphQLNonNull(ttype)
		if result.GetError() != nil {
			t.Fatalf(`unexpected error: %v for type "%v"`, result.GetError(), ttype)
		}
	}
}
Example #18
0
func TestLists_NullableListOfNonNullObjects_ReturnsNull(t *testing.T) {
	ttype := types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt))

	expected := &types.GraphQLResult{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": nil,
			},
		},
	}
	checkList(t, ttype, nil, expected)
}
Example #19
0
// Describe [T!]! Func()Array<T> // equivalent to Promise<Array<T>>
func TestLists_NonNullListOfNonNullFunc_ContainsValues(t *testing.T) {
	ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)))

	// `data` is a function that return values
	// Note that its uses the expected signature `func() interface{} {...}`
	data := func() interface{} {
		return []interface{}{
			1, 2,
		}
	}
	expected := &types.GraphQLResult{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": []interface{}{
					1, 2,
				},
			},
		},
	}
	checkList(t, ttype, data, expected)
}
func init() {
	throwingData["nest"] = func() interface{} {
		return throwingData
	}
	throwingData["nonNullNest"] = func() interface{} {
		return throwingData
	}
	throwingData["promiseNest"] = func() interface{} {
		return throwingData
	}
	throwingData["nonNullPromiseNest"] = func() interface{} {
		return throwingData
	}

	nullingData["nest"] = func() interface{} {
		return nullingData
	}
	nullingData["nonNullNest"] = func() interface{} {
		return nullingData
	}
	nullingData["promiseNest"] = func() interface{} {
		return nullingData
	}
	nullingData["nonNullPromiseNest"] = func() interface{} {
		return nullingData
	}

	dataType.AddFieldConfig("nest", &types.GraphQLFieldConfig{
		Type: dataType,
	})
	dataType.AddFieldConfig("nonNullNest", &types.GraphQLFieldConfig{
		Type: types.NewGraphQLNonNull(dataType),
	})
	dataType.AddFieldConfig("promiseNest", &types.GraphQLFieldConfig{
		Type: dataType,
	})
	dataType.AddFieldConfig("nonNullPromiseNest", &types.GraphQLFieldConfig{
		Type: types.NewGraphQLNonNull(dataType),
	})
}
Example #21
0
/*
 Given a function to map from an ID to an underlying object, and a function
 to map from an underlying object to the concrete GraphQLObjectType it
 corresponds to, constructs a `Node` interface that objects can implement,
 and a field config for a `node` root field.

 If the typeResolver is omitted, object resolution on the interface will be
 handled with the `isTypeOf` method on object types, as with any GraphQL
interface without a provided `resolveType` method.
*/
func NewNodeDefinitions(config NodeDefinitionsConfig) *NodeDefinitions {
	nodeInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{
		Name:        "Node",
		Description: "An object with an ID",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLNonNull(types.GraphQLID),
				Description: "The id of the object",
			},
		},
		ResolveType: config.TypeResolve,
	})

	nodeField := &types.GraphQLFieldConfig{
		Name:        "Node",
		Description: "Fetches an object given its ID",
		Type:        nodeInterface,
		Args: types.GraphQLFieldConfigArgumentMap{
			"id": &types.GraphQLArgumentConfig{
				Type:        types.NewGraphQLNonNull(types.GraphQLID),
				Description: "The ID of an object",
			},
		},
		Resolve: func(p types.GQLFRParams) interface{} {
			if config.IdFetcher == nil {
				return nil
			}
			id := ""
			if iid, ok := p.Args["id"]; ok {
				id = fmt.Sprintf("%v", iid)
			}
			fetchedId := config.IdFetcher(id, p.Info)
			return fetchedId
		},
	}
	return &NodeDefinitions{
		NodeInterface: nodeInterface,
		NodeField:     nodeField,
	}
}
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 := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Image",
		Fields: types.GraphQLFieldConfigMap{
			"url": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
			"width": &types.GraphQLFieldConfig{
				Type: types.GraphQLInt,
			},
			"height": &types.GraphQLFieldConfig{
				Type: types.GraphQLInt,
			},
		},
	})
	blogAuthor := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Author",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
			"name": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
			"pic": &types.GraphQLFieldConfig{
				Type: blogImage,
				Args: types.GraphQLFieldConfigArgumentMap{
					"width": &types.GraphQLArgumentConfig{
						Type: types.GraphQLInt,
					},
					"height": &types.GraphQLArgumentConfig{
						Type: types.GraphQLInt,
					},
				},
				Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
					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)
					}
					return nil
				},
			},
			"recentArticle": &types.GraphQLFieldConfig{},
		},
	})
	blogArticle := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Article",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type: types.NewGraphQLNonNull(types.GraphQLString),
			},
			"isPublished": &types.GraphQLFieldConfig{
				Type: types.GraphQLBoolean,
			},
			"author": &types.GraphQLFieldConfig{
				Type: blogAuthor,
			},
			"title": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
			"body": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
			"keywords": &types.GraphQLFieldConfig{
				Type: types.NewGraphQLList(types.GraphQLString),
			},
		},
	})

	blogAuthor.AddFieldConfig("recentArticle", &types.GraphQLFieldConfig{
		Type: blogArticle,
	})

	blogQuery := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Query",
		Fields: types.GraphQLFieldConfigMap{
			"article": &types.GraphQLFieldConfig{
				Type: blogArticle,
				Args: types.GraphQLFieldConfigArgumentMap{
					"id": &types.GraphQLArgumentConfig{
						Type: types.GraphQLID,
					},
				},
				Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
					id := p.Args["id"]
					return article(id)
				},
			},
			"feed": &types.GraphQLFieldConfig{
				Type: types.NewGraphQLList(blogArticle),
				Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
					return []*testArticle{
						article(1),
						article(2),
						article(3),
						article(4),
						article(5),
						article(6),
						article(7),
						article(8),
						article(9),
						article(10),
					}
				},
			},
		},
	})

	blogSchema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		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 := &types.GraphQLResult{
		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.Parse(t, request)

	// execute
	ep := executor.ExecuteParams{
		Schema: blogSchema,
		AST:    ast,
	}
	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))
	}
}
Example #23
0
	Cursor ConnectionCursor `json:"cursor"`
}
type GraphQLConnectionDefinitions struct {
	EdgeType       *types.GraphQLObjectType `json:"edgeType"`
	ConnectionType *types.GraphQLObjectType `json:"connectionType"`
}

/*
The common page info type used by all connections.
*/
var pageInfoType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
	Name:        "PageInfo",
	Description: "Information about pagination in a connection.",
	Fields: types.GraphQLFieldConfigMap{
		"hasNextPage": &types.GraphQLFieldConfig{
			Type:        types.NewGraphQLNonNull(types.GraphQLBoolean),
			Description: "When paginating forwards, are there more items?",
		},
		"hasPreviousPage": &types.GraphQLFieldConfig{
			Type:        types.NewGraphQLNonNull(types.GraphQLBoolean),
			Description: "When paginating backwards, are there more items?",
		},
		"startCursor": &types.GraphQLFieldConfig{
			Type:        types.GraphQLString,
			Description: "When paginating backwards, the cursor to continue.",
		},
		"endCursor": &types.GraphQLFieldConfig{
			Type:        types.GraphQLString,
			Description: "When paginating forwards, the cursor to continue.",
		},
	},
	"promise": func() interface{} {
		return nil
	},
	"nonNullPromise": func() interface{} {
		return nil
	},
}

var dataType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
	Name: "DataType",
	Fields: types.GraphQLFieldConfigMap{
		"sync": &types.GraphQLFieldConfig{
			Type: types.GraphQLString,
		},
		"nonNullSync": &types.GraphQLFieldConfig{
			Type: types.NewGraphQLNonNull(types.GraphQLString),
		},
		"promise": &types.GraphQLFieldConfig{
			Type: types.GraphQLString,
		},
		"nonNullPromise": &types.GraphQLFieldConfig{
			Type: types.NewGraphQLNonNull(types.GraphQLString),
		},
	},
})

var nonNullTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{
	Query: dataType,
})

func init() {
Example #25
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 := types.NewGraphQLEnumType(types.GraphQLEnumTypeConfig{
		Name:        "Episode",
		Description: "One of the films in the Star Wars Trilogy",
		Values: types.GraphQLEnumValueConfigMap{
			"NEWHOPE": &types.GraphQLEnumValueConfig{
				Value:       4,
				Description: "Released in 1977.",
			},
			"EMPIRE": &types.GraphQLEnumValueConfig{
				Value:       5,
				Description: "Released in 1980.",
			},
			"JEDI": &types.GraphQLEnumValueConfig{
				Value:       6,
				Description: "Released in 1983.",
			},
		},
	})

	characterInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{
		Name:        "Character",
		Description: "A character in the Star Wars Trilogy",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLNonNull(types.GraphQLString),
				Description: "The id of the character.",
			},
			"name": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The name of the character.",
			},
			"appearsIn": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(episodeEnum),
				Description: "Which movies they appear in.",
			},
		},
		ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType {
			if character, ok := value.(StarWarsChar); ok {
				id, _ := strconv.Atoi(character.Id)
				human := GetHuman(id)
				if human.Id != "" {
					return humanType
				}
			}
			return droidType
		},
	})
	characterInterface.AddFieldConfig("friends", &types.GraphQLFieldConfig{
		Type:        types.NewGraphQLList(characterInterface),
		Description: "The friends of the character, or an empty list if they have none.",
	})

	humanType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:        "Human",
		Description: "A humanoid creature in the Star Wars universe.",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLNonNull(types.GraphQLString),
				Description: "The id of the human.",
				Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Id
					}
					return nil
				},
			},
			"name": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The name of the human.",
				Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Name
					}
					return nil
				},
			},
			"friends": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(characterInterface),
				Description: "The friends of the human, or an empty list if they have none.",
				Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Friends
					}
					return []interface{}{}
				},
			},
			"appearsIn": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(episodeEnum),
				Description: "Which movies they appear in.",
				Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.AppearsIn
					}
					return nil
				},
			},
			"homePlanet": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The home planet of the human, or null if unknown.",
				Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.HomePlanet
					}
					return nil
				},
			},
		},
		Interfaces: []*types.GraphQLInterfaceType{
			characterInterface,
		},
	})
	droidType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:        "Droid",
		Description: "A mechanical creature in the Star Wars universe.",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLNonNull(types.GraphQLString),
				Description: "The id of the droid.",
				Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.Id
					}
					return nil
				},
			},
			"name": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The name of the droid.",
				Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.Name
					}
					return nil
				},
			},
			"friends": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(characterInterface),
				Description: "The friends of the droid, or an empty list if they have none.",
				Resolve: func(ctx context.Context, p types.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": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(episodeEnum),
				Description: "Which movies they appear in.",
				Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.AppearsIn
					}
					return nil
				},
			},
			"primaryFunction": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The primary function of the droid.",
				Resolve: func(ctx context.Context, p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.PrimaryFunction
					}
					return nil
				},
			},
		},
		Interfaces: []*types.GraphQLInterfaceType{
			characterInterface,
		},
	})

	queryType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Query",
		Fields: types.GraphQLFieldConfigMap{
			"hero": &types.GraphQLFieldConfig{
				Type: characterInterface,
				Args: types.GraphQLFieldConfigArgumentMap{
					"episode": &types.GraphQLArgumentConfig{
						Description: "If omitted, returns the hero of the whole saga. If " +
							"provided, returns the hero of that particular episode.",
						Type: episodeEnum,
					},
				},
				Resolve: func(ctx context.Context, p types.GQLFRParams) (r interface{}) {
					return GetHero(p.Args["episode"])
				},
			},
			"human": &types.GraphQLFieldConfig{
				Type: humanType,
				Args: types.GraphQLFieldConfigArgumentMap{
					"id": &types.GraphQLArgumentConfig{
						Description: "id of the human",
						Type:        types.NewGraphQLNonNull(types.GraphQLString),
					},
				},
				Resolve: func(ctx context.Context, p types.GQLFRParams) (r interface{}) {
					return GetHuman(p.Args["id"].(int))
				},
			},
			"droid": &types.GraphQLFieldConfig{
				Type: droidType,
				Args: types.GraphQLFieldConfigArgumentMap{
					"id": &types.GraphQLArgumentConfig{
						Description: "id of the droid",
						Type:        types.NewGraphQLNonNull(types.GraphQLString),
					},
				},
				Resolve: func(ctx context.Context, p types.GQLFRParams) (r interface{}) {
					return GetDroid(p.Args["id"].(int))
				},
			},
		},
	})
	StarWarsSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: queryType,
	})
}