예제 #1
0
func init() {
	nodeTestUserType = graphql.NewObject(graphql.ObjectConfig{
		Name: "User",
		Fields: graphql.Fields{
			"id": &graphql.Field{
				Type: graphql.NewNonNull(graphql.ID),
			},
			"name": &graphql.Field{
				Type: graphql.String,
			},
		},
		Interfaces: []*graphql.Interface{nodeTestDef.NodeInterface},
	})
	nodeTestPhotoType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Photo",
		Fields: graphql.Fields{
			"id": &graphql.Field{
				Type: graphql.NewNonNull(graphql.ID),
			},
			"width": &graphql.Field{
				Type: graphql.Int,
			},
		},
		Interfaces: []*graphql.Interface{nodeTestDef.NodeInterface},
	})

	nodeTestSchema, _ = graphql.NewSchema(graphql.SchemaConfig{
		Query: nodeTestQueryType,
	})
}
예제 #2
0
func schemaWithArgOfType(ttype graphql.Type) (graphql.Schema, error) {

	badObject := graphql.NewObject(graphql.ObjectConfig{
		Name: "BadObject",
		Fields: graphql.Fields{
			"badField": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"badArg": &graphql.ArgumentConfig{
						Type: ttype,
					},
				},
			},
		},
	})
	return graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "Query",
			Fields: graphql.Fields{
				"f": &graphql.Field{
					Type: badObject,
				},
			},
		}),
	})
}
예제 #3
0
func init() {
	globalIDTestUserType = graphql.NewObject(graphql.ObjectConfig{
		Name: "User",
		Fields: graphql.Fields{
			"id": relay.GlobalIDField("User", nil),
			"name": &graphql.Field{
				Type: graphql.String,
			},
		},
		Interfaces: []*graphql.Interface{globalIDTestDef.NodeInterface},
	})
	photoIDFetcher := func(obj interface{}, info graphql.ResolveInfo, ctx context.Context) (string, error) {
		switch obj := obj.(type) {
		case *photo2:
			return fmt.Sprintf("%v", obj.PhotoId), nil
		}
		return "", errors.New("Not a photo")
	}
	globalIDTestPhotoType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Photo",
		Fields: graphql.Fields{
			"id": relay.GlobalIDField("Photo", photoIDFetcher),
			"width": &graphql.Field{
				Type: graphql.Int,
			},
		},
		Interfaces: []*graphql.Interface{globalIDTestDef.NodeInterface},
	})

	globalIDTestSchema, _ = graphql.NewSchema(graphql.SchemaConfig{
		Query: globalIDTestQueryType,
	})
}
예제 #4
0
func TestMutation_ExecutionAddsErrorsFromFieldResolveFn(t *testing.T) {
	mError := errors.New("mutationError")
	q := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"a": &graphql.Field{
				Type: graphql.String,
			},
		},
	})
	m := graphql.NewObject(graphql.ObjectConfig{
		Name: "Mutation",
		Fields: graphql.Fields{
			"foo": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"f": &graphql.ArgumentConfig{
						Type: graphql.String,
					},
				},
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return nil, mError
				},
			},
			"bar": &graphql.Field{
				Type: graphql.String,
				Args: graphql.FieldConfigArgument{
					"b": &graphql.ArgumentConfig{
						Type: graphql.String,
					},
				},
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return "ok", nil
				},
			},
		},
	})
	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query:    q,
		Mutation: m,
	})
	if err != nil {
		t.Fatalf("unexpected error, got: %v", err)
	}
	query := "mutation _ { newFoo: foo(f:\"title\") }"
	result := graphql.Do(graphql.Params{
		Schema:        schema,
		RequestString: query,
	})
	if len(result.Errors) == 0 {
		t.Fatal("wrong result, expected errors, got no errors")
	}
	if result.Errors[0].Error() != mError.Error() {
		t.Fatalf("wrong result, unexpected error, got: %v, expected: %v", result.Errors[0], mError)
	}
}
예제 #5
0
func TestTypeSystem_DefinitionExample_IncludesNestedInputObjectsInTheMap(t *testing.T) {
	nestedInputObject := graphql.NewInputObject(graphql.InputObjectConfig{
		Name: "NestedInputObject",
		Fields: graphql.InputObjectConfigFieldMap{
			"value": &graphql.InputObjectFieldConfig{
				Type: graphql.String,
			},
		},
	})
	someInputObject := graphql.NewInputObject(graphql.InputObjectConfig{
		Name: "SomeInputObject",
		Fields: graphql.InputObjectConfigFieldMap{
			"nested": &graphql.InputObjectFieldConfig{
				Type: nestedInputObject,
			},
		},
	})
	someMutation := graphql.NewObject(graphql.ObjectConfig{
		Name: "SomeMutation",
		Fields: graphql.Fields{
			"mutateSomething": &graphql.Field{
				Type: blogArticle,
				Args: graphql.FieldConfigArgument{
					"input": &graphql.ArgumentConfig{
						Type: someInputObject,
					},
				},
			},
		},
	})
	someSubscription := graphql.NewObject(graphql.ObjectConfig{
		Name: "SomeSubscription",
		Fields: graphql.Fields{
			"subscribeToSomething": &graphql.Field{
				Type: blogArticle,
				Args: graphql.FieldConfigArgument{
					"input": &graphql.ArgumentConfig{
						Type: someInputObject,
					},
				},
			},
		},
	})
	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query:        blogQuery,
		Mutation:     someMutation,
		Subscription: someSubscription,
	})
	if err != nil {
		t.Fatalf("unexpected error, got: %v", err)
	}
	if schema.Type("NestedInputObject") != nestedInputObject {
		t.Fatalf(`schema.GetType("NestedInputObject") expected to equal nestedInputObject, got: %v`, schema.Type("NestedInputObject"))
	}
}
예제 #6
0
func TestUsesTheSubscriptionSchemaForSubscriptions(t *testing.T) {

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

	expected := &graphql.Result{
		Data: map[string]interface{}{
			"a": "b",
		},
	}

	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "Q",
			Fields: graphql.Fields{
				"a": &graphql.Field{
					Type: graphql.String,
				},
			},
		}),
		Subscription: graphql.NewObject(graphql.ObjectConfig{
			Name: "S",
			Fields: graphql.Fields{
				"a": &graphql.Field{
					Type: graphql.String,
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

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

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

	anotherInterface := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			return nil
		},
		Fields: graphql.Fields{
			"f": &graphql.Field{
				Type: graphql.String,
			},
		},
	})
	FirstBadObject := graphql.NewObject(graphql.ObjectConfig{
		Name: "BadObject",
		Interfaces: []*graphql.Interface{
			anotherInterface,
		},
		Fields: graphql.Fields{
			"f": &graphql.Field{
				Type: graphql.String,
			},
		},
	})
	SecondBadObject := graphql.NewObject(graphql.ObjectConfig{
		Name: "BadObject",
		Interfaces: []*graphql.Interface{
			anotherInterface,
		},
		Fields: graphql.Fields{
			"f": &graphql.Field{
				Type: graphql.String,
			},
		},
	})
	queryType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"iface": &graphql.Field{
				Type: anotherInterface,
			},
		},
	})
	_, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: queryType,
		Types: []graphql.Type{FirstBadObject, SecondBadObject},
	})
	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)
	}
}
예제 #8
0
func TestDoesNotIncludeIllegalFieldsInOutput(t *testing.T) {

	doc := `mutation M {
      thisIsIllegalDontIncludeMe
    }`

	expected := &graphql.Result{
		Data: map[string]interface{}{},
	}

	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "Q",
			Fields: graphql.Fields{
				"a": &graphql.Field{
					Type: graphql.String,
				},
			},
		}),
		Mutation: graphql.NewObject(graphql.ObjectConfig{
			Name: "M",
			Fields: graphql.Fields{
				"c": &graphql.Field{
					Type: graphql.String,
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

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

	// execute
	ep := graphql.ExecuteParams{
		Schema: schema,
		AST:    ast,
	}
	result := testutil.TestExecute(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))
	}
}
예제 #9
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)
	}
}
예제 #10
0
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectMissingAnInterfaceArgument(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,
			},
		},
	})
	_, 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)
	}
}
예제 #11
0
func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichRedefinesABuiltInType(t *testing.T) {

	fakeString := graphql.NewScalar(graphql.ScalarConfig{
		Name: "String",
		Serialize: func(value interface{}) interface{} {
			return nil
		},
	})
	queryType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"normal": &graphql.Field{
				Type: graphql.String,
			},
			"fake": &graphql.Field{
				Type: fakeString,
			},
		},
	})
	_, err := graphql.NewSchema(graphql.SchemaConfig{
		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)
	}
}
예제 #12
0
func TestQuery_ExecutionDoesNotAddErrorsFromFieldResolveFn(t *testing.T) {
	qError := errors.New("queryError")
	q := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"a": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return nil, qError
				},
			},
			"b": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return "ok", nil
				},
			},
		},
	})
	blogSchema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: q,
	})
	if err != nil {
		t.Fatalf("unexpected error, got: %v", err)
	}
	query := "{ b }"
	result := graphql.Do(graphql.Params{
		Schema:        blogSchema,
		RequestString: query,
	})
	if len(result.Errors) != 0 {
		t.Fatalf("wrong result, unexpected errors: %+v", result.Errors)
	}
}
예제 #13
0
func main() {
	// Schema
	fields := graphql.Fields{
		"hello": &graphql.Field{
			Type: graphql.String,
			Resolve: func(p graphql.ResolveParams) (interface{}, error) {
				return "world", nil
			},
		},
	}
	rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields}
	schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}
	schema, err := graphql.NewSchema(schemaConfig)
	if err != nil {
		log.Fatalf("failed to create new schema, error: %v", err)
	}

	// Query
	query := `
		{
			hello
		}
	`
	params := graphql.Params{Schema: schema, RequestString: query}
	r := graphql.Do(params)
	if len(r.Errors) > 0 {
		log.Fatalf("failed to execute graphql operation, errors: %+v", r.Errors)
	}
	rJSON, _ := json.Marshal(r)
	fmt.Printf("%s \n", rJSON) // {“data”:{“hello”:”world”}}
}
예제 #14
0
func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceTypeDefiningResolveTypeWithImplementingTypeDefiningIsTypeOf(t *testing.T) {

	anotherInterfaceType := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			return nil
		},
		Fields: graphql.Fields{
			"f": &graphql.Field{
				Type: graphql.String,
			},
		},
	})
	_, err := schemaWithFieldType(graphql.NewObject(graphql.ObjectConfig{
		Name:       "SomeObject",
		Interfaces: []*graphql.Interface{anotherInterfaceType},
		IsTypeOf: func(p graphql.IsTypeOfParams) bool {
			return true
		},
		Fields: graphql.Fields{
			"f": &graphql.Field{
				Type: graphql.String,
			},
		},
	}))
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}
예제 #15
0
func TestDirectives_DirectivesMustBeNamed(t *testing.T) {
	invalidDirective := graphql.NewDirective(graphql.DirectiveConfig{
		Locations: []string{
			graphql.DirectiveLocationField,
		},
	})
	_, 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:   "Directive must be named.",
		Locations: []location.SourceLocation{},
	}
	if !reflect.DeepEqual(expectedErr, err) {
		t.Fatalf("Expected error to be equal, got: %v", testutil.Diff(expectedErr, err))
	}
}
예제 #16
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)
	}
}
예제 #17
0
func TestDirectives_DirectiveNameMustBeValid(t *testing.T) {
	invalidDirective := graphql.NewDirective(graphql.DirectiveConfig{
		Name: "123invalid name",
		Locations: []string{
			graphql.DirectiveLocationField,
		},
	})
	_, 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 "123invalid name" does not.`,
		Locations: []location.SourceLocation{},
	}
	if !reflect.DeepEqual(expectedErr, err) {
		t.Fatalf("Expected error to be equal, got: %v", testutil.Diff(expectedErr, err))
	}
}
예제 #18
0
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWithASubtypedInterfaceField_Interface(t *testing.T) {
	var anotherInterface *graphql.Interface
	anotherInterface = graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			return nil
		},
		Fields: (graphql.FieldsThunk)(func() graphql.Fields {
			return graphql.Fields{
				"field": &graphql.Field{
					Type: anotherInterface,
				},
			}
		}),
	})
	var anotherObject *graphql.Object
	anotherObject = graphql.NewObject(graphql.ObjectConfig{
		Name:       "AnotherObject",
		Interfaces: []*graphql.Interface{anotherInterface},
		Fields: (graphql.FieldsThunk)(func() graphql.Fields {
			return graphql.Fields{
				"field": &graphql.Field{
					Type: anotherObject,
				},
			}
		}),
	})
	_, err := schemaWithFieldType(anotherObject)
	if err != nil {
		t.Fatalf(`unexpected error: %v for type "%v"`, err, anotherObject)
	}
}
예제 #19
0
func TestTypeSystem_ObjectInterfacesMustBeArray_AcceptsAnObjectTypeWithInterfacesAsFunctionReturningAnArray(t *testing.T) {
	anotherInterfaceType := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			return nil
		},
		Fields: graphql.Fields{
			"f": &graphql.Field{
				Type: graphql.String,
			},
		},
	})
	_, err := schemaWithFieldType(graphql.NewObject(graphql.ObjectConfig{
		Name:       "SomeObject",
		Interfaces: []*graphql.Interface{anotherInterfaceType},
		Fields: graphql.Fields{
			"f": &graphql.Field{
				Type: graphql.String,
			},
		},
	}))
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}
예제 #20
0
func TestIntrospection_IdentifiesDeprecatedFields(t *testing.T) {

	testType := graphql.NewObject(graphql.ObjectConfig{
		Name: "TestType",
		Fields: graphql.Fields{
			"nonDeprecated": &graphql.Field{
				Type: graphql.String,
			},
			"deprecated": &graphql.Field{
				Type:              graphql.String,
				DeprecationReason: "Removed in 1.0",
			},
		},
	})
	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: testType,
	})
	if err != nil {
		t.Fatalf("Error creating Schema: %v", err.Error())
	}
	query := `
      {
        __type(name: "TestType") {
          name
          fields(includeDeprecated: true) {
            name
            isDeprecated,
            deprecationReason
          }
        }
      }
    `
	expected := &graphql.Result{
		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 := g(t, graphql.Params{
		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))
	}
}
예제 #21
0
func TestCorrectlyThreadsArguments(t *testing.T) {

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

	var resolvedArgs map[string]interface{}

	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "Type",
			Fields: graphql.Fields{
				"b": &graphql.Field{
					Args: graphql.FieldConfigArgument{
						"numArg": &graphql.ArgumentConfig{
							Type: graphql.Int,
						},
						"stringArg": &graphql.ArgumentConfig{
							Type: graphql.String,
						},
					},
					Type: graphql.String,
					Resolve: func(p graphql.ResolveParams) (interface{}, error) {
						resolvedArgs = p.Args
						return resolvedArgs, nil
					},
				},
			},
		}),
	})
	if err != nil {
		t.Fatalf("Error in schema %v", err.Error())
	}

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

	// execute
	ep := graphql.ExecuteParams{
		Schema: schema,
		AST:    ast,
	}
	result := testutil.TestExecute(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"])
	}
}
예제 #22
0
func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWithADifferentlyTypeInterfaceField(t *testing.T) {

	typeA := graphql.NewObject(graphql.ObjectConfig{
		Name: "A",
		Fields: graphql.Fields{
			"foo": &graphql.Field{
				Type: graphql.String,
			},
		},
	})
	typeB := graphql.NewObject(graphql.ObjectConfig{
		Name: "B",
		Fields: graphql.Fields{
			"foo": &graphql.Field{
				Type: graphql.String,
			},
		},
	})

	anotherInterface := graphql.NewInterface(graphql.InterfaceConfig{
		Name: "AnotherInterface",
		ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
			return nil
		},
		Fields: graphql.Fields{
			"field": &graphql.Field{
				Type: typeA,
			},
		},
	})
	anotherObject := graphql.NewObject(graphql.ObjectConfig{
		Name:       "AnotherObject",
		Interfaces: []*graphql.Interface{anotherInterface},
		Fields: graphql.Fields{
			"field": &graphql.Field{
				Type: typeB,
			},
		},
	})
	_, err := schemaWithObjectFieldOfType(anotherObject)
	expectedError := `AnotherInterface.field expects type "A" but AnotherObject.field provides type "B".`
	if err == nil || err.Error() != expectedError {
		t.Fatalf("Expected error: %v, got %v", expectedError, err)
	}
}
예제 #23
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,
	}
}
예제 #24
0
func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithMissingFields(t *testing.T) {
	badObject := graphql.NewObject(graphql.ObjectConfig{
		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)
	}
}
예제 #25
0
func TestTypeSystem_DefinitionExample_IncludesInterfacesThunkSubtypesInTheTypeMap(t *testing.T) {

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

	someSubType := graphql.NewObject(graphql.ObjectConfig{
		Name: "SomeSubtype",
		Fields: graphql.Fields{
			"f": &graphql.Field{
				Type: graphql.Int,
			},
		},
		Interfaces: (graphql.InterfacesThunk)(func() []*graphql.Interface {
			return []*graphql.Interface{someInterface}
		}),
		IsTypeOf: func(p graphql.IsTypeOfParams) bool {
			return true
		},
	})
	schema, err := graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "Query",
			Fields: graphql.Fields{
				"iface": &graphql.Field{
					Type: someInterface,
				},
			},
		}),
		Types: []graphql.Type{someSubType},
	})
	if err != nil {
		t.Fatalf("unexpected error, got: %v", err)
	}
	if schema.Type("SomeSubtype") != someSubType {
		t.Fatalf(`schema.GetType("SomeSubtype") expected to equal someSubType, got: %v`, schema.Type("SomeSubtype"))
	}
}
예제 #26
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
		},
	}
}
예제 #27
0
func schemaWithObjectFieldOfType(fieldType graphql.Input) (graphql.Schema, error) {

	badObjectType := graphql.NewObject(graphql.ObjectConfig{
		Name: "BadObject",
		Fields: graphql.Fields{
			"badField": &graphql.Field{
				Type: fieldType,
			},
		},
	})
	return graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "Query",
			Fields: graphql.Fields{
				"f": &graphql.Field{
					Type: badObjectType,
				},
			},
		}),
	})
}
예제 #28
0
func schemaWithFieldType(ttype graphql.Output) (graphql.Schema, error) {
	return graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "Query",
			Fields: graphql.Fields{
				"f": &graphql.Field{
					Type: ttype,
				},
			},
		}),
		Types: []graphql.Type{ttype},
	})
}
예제 #29
0
func TestTypeSystem_ObjectsMustHaveFields_AcceptsAnObjectTypeWithFieldsObject(t *testing.T) {
	_, err := schemaWithFieldType(graphql.NewObject(graphql.ObjectConfig{
		Name: "SomeObject",
		Fields: graphql.Fields{
			"f": &graphql.Field{
				Type: graphql.String,
			},
		},
	}))
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}
예제 #30
0
func schemaWithObjectImplementingType(implementedType *graphql.Interface) (graphql.Schema, error) {

	badObjectType := graphql.NewObject(graphql.ObjectConfig{
		Name:       "BadObject",
		Interfaces: []*graphql.Interface{implementedType},
		Fields: graphql.Fields{
			"f": &graphql.Field{
				Type: graphql.String,
			},
		},
	})
	return graphql.NewSchema(graphql.SchemaConfig{
		Query: graphql.NewObject(graphql.ObjectConfig{
			Name: "Query",
			Fields: graphql.Fields{
				"f": &graphql.Field{
					Type: badObjectType,
				},
			},
		}),
		Types: []graphql.Type{badObjectType},
	})
}