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

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

	globalIDTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: globalIDTestQueryType,
	})
}
func schemaWithArgOfType(ttype types.GraphQLType) (types.GraphQLSchema, error) {

	badObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "BadObject",
		Fields: types.GraphQLFieldConfigMap{
			"badField": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
				Args: types.GraphQLFieldConfigArgumentMap{
					"badArg": &types.GraphQLArgumentConfig{
						Type: ttype,
					},
				},
			},
		},
	})
	return types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Query",
			Fields: types.GraphQLFieldConfigMap{
				"f": &types.GraphQLFieldConfig{
					Type: badObject,
				},
			},
		}),
	})
}
func init() {
	postType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Post",
		Fields: types.GraphQLFieldConfigMap{
			// Define `id` field as a Relay GlobalID field.
			// It helps with translating your GraphQL object's id into a global id
			// For eg:
			// 		For a `Post` type, with an id of `1`, it's global id will be `UG9zdDox`
			//      which is a base64 encoded version of `Post:1` string
			// We will explore more in the next part of this series.
			"id": gqlrelay.GlobalIdField("Post", nil),
			"text": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})

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

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

}
示例#5
0
func TestUsesTheMutationSchemaForQueries(t *testing.T) {

	doc := `query Q { a } mutation M { c }`
	data := map[string]interface{}{
		"a": "b",
		"c": "d",
	}

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

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

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

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

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

	doc := `mutation M {
      thisIsIllegalDontIncludeMe
    }`

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

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

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

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

	fakeString := types.NewGraphQLScalarType(types.GraphQLScalarTypeConfig{
		Name: "String",
		Serialize: func(value interface{}) interface{} {
			return nil
		},
	})
	queryType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Query",
		Fields: types.GraphQLFieldConfigMap{
			"normal": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
			"fake": &types.GraphQLFieldConfig{
				Type: fakeString,
			},
		},
	})
	_, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: queryType,
	})
	expectedError := `Schema must contain unique named types but contains multiple types named "String".`
	if err == nil || err.Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, err)
	}
}
func 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)
	}
}
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 TestTypeSystem_ObjectInterfacesMustBeArray_AcceptsAnObjectTypeWithInterfacesAsFunctionReturningAnArray(t *testing.T) {
	anotherInterfaceType := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{
		Name: "AnotherInterface",
		ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType {
			return nil
		},
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	_, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:       "SomeObject",
		Interfaces: []*types.GraphQLInterfaceType{anotherInterfaceType},
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	}))
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectMissingAnInterfaceArgument(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,
				Args: types.GraphQLFieldConfigArgumentMap{
					"input": &types.GraphQLArgumentConfig{
						Type: types.GraphQLString,
					},
				},
			},
		},
	})
	anotherObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:       "AnotherObject",
		Interfaces: []*types.GraphQLInterfaceType{anotherInterface},
		Fields: types.GraphQLFieldConfigMap{
			"field": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	_, err := schemaWithObjectFieldOfType(anotherObject)
	expectedError := `AnotherInterface.field expects argument "input" but AnotherObject.field does not provide it.`
	if err == nil || err.Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, err)
	}
}
func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceTypeDefiningResolveTypeWithImplementingTypeDefiningIsTypeOf(t *testing.T) {

	anotherInterfaceType := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{
		Name: "AnotherInterface",
		ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType {
			return nil
		},
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	_, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:       "SomeObject",
		Interfaces: []*types.GraphQLInterfaceType{anotherInterfaceType},
		IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool {
			return true
		},
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	}))
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}
func TestIntrospection_IdentifiesDeprecatedFields(t *testing.T) {

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

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

	var resolvedArgs map[string]interface{}

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

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

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

	expectedNum := 123
	expectedString := "foo"
	if resolvedArgs["numArg"] != expectedNum {
		t.Fatalf("Expected args.numArg to equal `%v`, got `%v`", expectedNum, resolvedArgs["numArg"])
	}
	if resolvedArgs["stringArg"] != expectedString {
		t.Fatalf("Expected args.stringArg to equal `%v`, got `%v`", expectedNum, resolvedArgs["stringArg"])
	}
}
示例#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_ObjectsMustHaveFields_RejectsAnObjectTypeWithMissingFields(t *testing.T) {
	badObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "SomeObject",
	})
	_, err := schemaWithFieldType(badObject)
	expectedError := `SomeObject fields must be an object with field names as keys or a function which return such an object.`
	if err == nil || err.Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, err)
	}
}
func TestTypeSystem_DefinitionExample_IncludesInterfacesThunkSubtypesInTheTypeMap(t *testing.T) {

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

	someSubType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "SomeSubtype",
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLInt,
			},
		},
		Interfaces: (types.GraphQLInterfacesThunk)(func() []*types.GraphQLInterfaceType {
			return []*types.GraphQLInterfaceType{someInterface}
		}),
		IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool {
			return true
		},
	})
	schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Query",
			Fields: types.GraphQLFieldConfigMap{
				"iface": &types.GraphQLFieldConfig{
					Type: someInterface,
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("unexpected error, got: %v", err)
	}
	if schema.GetType("SomeSubtype") != someSubType {
		t.Fatalf(`schema.GetType("SomeSubtype") expected to equal someSubType, got: %v`, schema.GetType("SomeSubtype"))
	}
}
func schemaWithObjectFieldOfType(fieldType types.GraphQLInputType) (types.GraphQLSchema, error) {

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

	badObjectType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:       "BadObject",
		Interfaces: []*types.GraphQLInterfaceType{implementedType},
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	return types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
			Name: "Query",
			Fields: types.GraphQLFieldConfigMap{
				"f": &types.GraphQLFieldConfig{
					Type: badObjectType,
				},
			},
		}),
	})
}
func TestTypeSystem_ObjectsMustHaveFields_AcceptsAnObjectTypeWithFieldsObject(t *testing.T) {
	_, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "SomeObject",
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	}))
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}
示例#23
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
		},
	}
}
func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichDefinesAnObjectTypeTwice(t *testing.T) {

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

	query := `
      query Example { a }
    `

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

	var resolvedContext map[string]interface{}

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

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

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

	expected := "thing"
	if resolvedContext["contextThing"] != expected {
		t.Fatalf("Expected context.contextThing to equal %v, got %v", expected, resolvedContext["contextThing"])
	}
}
func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithIncorrectlyNamedFields(t *testing.T) {
	badObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "SomeObject",
		Fields: types.GraphQLFieldConfigMap{
			"bad-name-with-dashes": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	_, err := schemaWithFieldType(badObject)
	expectedError := `Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "bad-name-with-dashes" does not.`
	if err == nil || err.Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, err)
	}
}
示例#27
0
func TestThrowsIfNoOperationIsProvidedWithMultipleOperations(t *testing.T) {

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

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

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

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

	// execute
	ep := executor.ExecuteParams{
		Schema: schema,
		AST:    ast,
		Root:   data,
	}
	result := testutil.Execute(t, ep)
	if len(result.Errors) != 1 {
		t.Fatalf("wrong result, expected len(1) unexpected len: %v", len(result.Errors))
	}
	if result.Data != nil {
		t.Fatalf("wrong result, expected nil result.Data, got %v", result.Data)
	}
	if !reflect.DeepEqual(expectedErrors, result.Errors) {
		t.Fatalf("unexpected result, Diff: %v", testutil.Diff(expectedErrors, result.Errors))
	}
}
func TestTypeSystem_ObjectTypesMustBeAssertable_AcceptsAnObjectTypeWithAnIsTypeOfFunction(t *testing.T) {
	_, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "AnotherObject",
		IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool {
			return true
		},
		Fields: types.GraphQLFieldConfigMap{
			"f": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	}))
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}
示例#29
0
func TestFailsToExecuteQueryContainingATypeDefinition(t *testing.T) {

	query := `
      { foo }

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

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

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

	// execute
	ep := executor.ExecuteParams{
		Schema: schema,
		AST:    ast,
	}
	result := testutil.Execute(t, ep)
	if len(result.Errors) != 1 {
		t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
	}
	if !reflect.DeepEqual(expected, result) {
		t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
	}
}
func TestTypeSystem_SchemaMustHaveObjectRootTypes_AcceptsASchemaWhoseQueryAndMutationTypesAreObjectType(t *testing.T) {
	mutationObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Mutation",
		Fields: types.GraphQLFieldConfigMap{
			"edit": &types.GraphQLFieldConfig{
				Type: types.GraphQLString,
			},
		},
	})
	_, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query:    someObjectType,
		Mutation: mutationObject,
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}