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

	return &graphql.FieldConfig{
		Description: config.Description,
		Type:        graphql.NewList(config.OutputType),
		Args:        inputArgs,
		Resolve: func(p graphql.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 #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)
		}
	}
}
Example #3
0
func init() {
	nodeTestUserType = graphql.NewObject(graphql.ObjectConfig{
		Name: "User",
		Fields: graphql.FieldConfigMap{
			"id": &graphql.FieldConfig{
				Type: graphql.NewNonNull(graphql.ID),
			},
			"name": &graphql.FieldConfig{
				Type: graphql.String,
			},
		},
		Interfaces: []*graphql.Interface{nodeTestDef.NodeInterface},
	})
	nodeTestPhotoType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Photo",
		Fields: graphql.FieldConfigMap{
			"id": &graphql.FieldConfig{
				Type: graphql.NewNonNull(graphql.ID),
			},
			"width": &graphql.FieldConfig{
				Type: graphql.Int,
			},
		},
		Interfaces: []*graphql.Interface{nodeTestDef.NodeInterface},
	})

	nodeTestSchema, _ = graphql.NewSchema(graphql.SchemaConfig{
		Query: nodeTestQueryType,
	})
}
Example #4
0
func TestTypeSystem_DefinitionExample_ProhibitsNestingNonNullInsideNonNull(t *testing.T) {
	ttype := graphql.NewNonNull(graphql.NewNonNull(graphql.Int))
	expected := `Can only create NonNull of a Nullable Type but got: Int!.`
	if ttype.Error().Error() != expected {
		t.Fatalf(`expected %v , got: %v`, expected, ttype.Error())
	}
}
Example #5
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, fmt.Errorf("Missing arg %q", config.ArgName)
			}

			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, fmt.Errorf("Can't handle %T", inputs)
		},
	}
}
Example #6
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{
			gqlerrors.FormattedError{
				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 #7
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)
	}
}
Example #8
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)
}
Example #9
0
func MutationWithClientMutationID(config MutationConfig) *graphql.Field {

	augmentedInputFields := config.InputFields
	if augmentedInputFields == nil {
		augmentedInputFields = graphql.InputObjectConfigFieldMap{}
	}
	augmentedInputFields["clientMutationId"] = &graphql.InputObjectFieldConfig{
		Type: graphql.NewNonNull(graphql.String),
	}
	augmentedOutputFields := config.OutputFields
	if augmentedOutputFields == nil {
		augmentedOutputFields = graphql.Fields{}
	}
	augmentedOutputFields["clientMutationId"] = &graphql.Field{
		Type: graphql.NewNonNull(graphql.String),
	}

	inputType := graphql.NewInputObject(graphql.InputObjectConfig{
		Name:   config.Name + "Input",
		Fields: augmentedInputFields,
	})
	outputType := graphql.NewObject(graphql.ObjectConfig{
		Name:   config.Name + "Payload",
		Fields: augmentedOutputFields,
	})
	return &graphql.Field{
		Name: config.Name,
		Type: outputType,
		Args: graphql.FieldConfigArgument{
			"input": &graphql.ArgumentConfig{
				Type: graphql.NewNonNull(inputType),
			},
		},
		Resolve: func(p graphql.ResolveParams) (interface{}, error) {
			if config.MutateAndGetPayload == nil {
				return nil, nil
			}
			input := map[string]interface{}{}
			if inputVal, ok := p.Args["input"]; ok {
				if inputVal, ok := inputVal.(map[string]interface{}); ok {
					input = inputVal
				}
			}
			payload, err := config.MutateAndGetPayload(input, p.Info, p.Context)
			if err != nil {
				return nil, err
			}
			if clientMutationID, ok := input["clientMutationId"]; ok {
				payload["clientMutationId"] = clientMutationID
			}
			return payload, nil
		},
	}
}
Example #10
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
}
Example #11
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)
		}
	}
}
Example #12
0
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWithSubsetNonNullInterfaceFieldType(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.NewNonNull(graphql.String),
			},
		},
	})
	_, err := schemaWithFieldType(anotherObject)
	if err != nil {
		t.Fatalf(`unexpected error: %v for type "%v"`, err, anotherObject)
	}
}
Example #13
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)
	}
}
Example #14
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)
}
Example #15
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{
			gqlerrors.FormattedError{
				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 #16
0
func TestTypeSystem_NonNullMustAcceptGraphQLTypes_RejectsNilAsNonNullableType(t *testing.T) {
	result := graphql.NewNonNull(nil)
	expectedError := `Can only create NonNull of a Nullable Type but got: <nil>.`
	if result.GetError() == nil || result.GetError().Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, result.GetError())
	}
}
Example #17
0
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWithASupersetNullableInterfaceFieldType(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.String),
			},
		},
	})
	anotherObject := graphql.NewObject(graphql.ObjectConfig{
		Name:       "AnotherObject",
		Interfaces: []*graphql.Interface{anotherInterface},
		Fields: graphql.Fields{
			"field": &graphql.Field{
				Type: 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)
	}
}
Example #18
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) *graphql.Field {
	return &graphql.Field{
		Name:        "id",
		Description: "The ID of an object",
		Type:        graphql.NewNonNull(graphql.ID),
		Resolve: func(p graphql.ResolveParams) (interface{}, error) {
			id := ""
			if idFetcher != nil {
				fetched, err := idFetcher(p.Source, p.Info, p.Context)
				id = fmt.Sprintf("%v", fetched)
				if err != nil {
					return id, err
				}
			} 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, nil
		},
	}
}
Example #19
0
func TestTypeSystem_DefinitionExample_ProhibitsNilInNonNull(t *testing.T) {
	ttype := graphql.NewNonNull(nil)
	expected := `Can only create NonNull of a Nullable Type but got: <nil>.`
	if ttype.GetError().Error() != expected {
		t.Fatalf(`expected %v , got: %v`, expected, ttype.GetError())
	}
}
Example #20
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,
	}
}
Example #21
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.GetError() != nil {
			t.Fatalf(`unexpected error: %v for type "%v"`, result.GetError(), ttype)
		}
	}
}
Example #22
0
// Describe [T!]! Func()Array<T> // equivalent to Promise<Array<T>>
func TestLists_NonNullListOfNonNullFunc_ContainsValues(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 []interface{}{
			1, 2,
		}
	}
	expected := &graphql.Result{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": []interface{}{
					1, 2,
				},
			},
		},
	}
	checkList(t, ttype, data, expected)
}
Example #23
0
func TestLists_NullableListOfNonNullObjects_ReturnsNull(t *testing.T) {
	ttype := graphql.NewList(graphql.NewNonNull(graphql.Int))

	expected := &graphql.Result{
		Data: map[string]interface{}{
			"nest": map[string]interface{}{
				"test": nil,
			},
		},
	}
	checkList(t, ttype, nil, expected)
}
Example #24
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 := graphql.NewInterface(graphql.InterfaceConfig{
		Name:        "Node",
		Description: "An object with an ID",
		Fields: graphql.FieldConfigMap{
			"id": &graphql.FieldConfig{
				Type:        graphql.NewNonNull(graphql.ID),
				Description: "The id of the object",
			},
		},
		ResolveType: config.TypeResolve,
	})

	nodeField := &graphql.FieldConfig{
		Name:        "Node",
		Description: "Fetches an object given its ID",
		Type:        nodeInterface,
		Args: graphql.FieldConfigArgument{
			"id": &graphql.ArgumentConfig{
				Type:        graphql.NewNonNull(graphql.ID),
				Description: "The ID of an object",
			},
		},
		Resolve: func(p graphql.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,
	}
}
Example #25
0
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", &graphql.FieldConfig{
		Type: dataType,
	})
	dataType.AddFieldConfig("nonNullNest", &graphql.FieldConfig{
		Type: graphql.NewNonNull(dataType),
	})
	dataType.AddFieldConfig("promiseNest", &graphql.FieldConfig{
		Type: dataType,
	})
	dataType.AddFieldConfig("nonNullPromiseNest", &graphql.FieldConfig{
		Type: graphql.NewNonNull(dataType),
	})
}
Example #26
0
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWhichImplementsAnInterfaceFieldAlongWithAdditionalRequiredArguments(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,
				Args: graphql.FieldConfigArgument{
					"input": &graphql.ArgumentConfig{
						Type: graphql.String,
					},
				},
			},
		},
	})
	anotherObject := graphql.NewObject(graphql.ObjectConfig{
		Name:       "AnotherObject",
		Interfaces: []*graphql.Interface{anotherInterface},
		Fields: graphql.Fields{
			"field": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"input": &graphql.ArgumentConfig{
						Type: graphql.String,
					},
					"anotherInput": &graphql.ArgumentConfig{
						Type: graphql.NewNonNull(graphql.String),
					},
				},
			},
		},
	})
	_, err := schemaWithObjectFieldOfType(anotherObject)
	expectedError := `AnotherObject.field(anotherInput:) is of required type "String!" but is not also provided by the interface AnotherInterface.field.`
	if err == nil || err.Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, err)
	}
}
Example #27
0
func TestDirectives_DirectiveArgNamesMustBeValid(t *testing.T) {
	invalidDirective := graphql.NewDirective(graphql.DirectiveConfig{
		Name: "skip",
		Description: "Directs the executor to skip this field or fragment when the `if` " +
			"argument is true.",
		Args: graphql.FieldConfigArgument{
			"123if": &graphql.ArgumentConfig{
				Type:        graphql.NewNonNull(graphql.Boolean),
				Description: "Skipped when true.",
			},
		},
		Locations: []string{
			graphql.DirectiveLocationField,
			graphql.DirectiveLocationFragmentSpread,
			graphql.DirectiveLocationInlineFragment,
		},
	})
	_, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "TestType",
			Fields: graphql.Fields{
				"a": &graphql.Field{
					Type: graphql.String,
				},
			},
		}),
		Directives: []*graphql.Directive{invalidDirective},
	})
	expectedErr := gqlerrors.FormattedError{
		Message:   `Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "123if" does not.`,
		Locations: []location.SourceLocation{},
	}
	if !reflect.DeepEqual(expectedErr, err) {
		t.Fatalf("Expected error to be equal, got: %v", testutil.Diff(expectedErr, err))
	}
}
Example #28
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,
	})
}
Example #29
0
		}
		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),
		},
		"nb": &graphql.InputObjectFieldConfig{
			Type: graphql.NewNonNull(graphql.String),
Example #30
0
		}
		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,
		},
	},
})

func inputResolved(p graphql.ResolveParams) interface{} {
	input, ok := p.Args["input"]
	if !ok {
		return nil
	}
	b, err := json.Marshal(input)
	if err != nil {
		return nil