graphql

package module
v0.0.0-...-316ec34 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 16, 2025 License: MIT Imports: 21 Imported by: 0

README

graphql Build Status GoDoc Coverage Status

A work-in-progress implementation of GraphQL for Go.

Getting Started

To install the library, run:

go get github.com/graphql-go/graphql

The following is a simple example which defines a schema with a single hello string-type field and a Resolve method which returns the string world. A GraphQL query is performed against this schema with the resulting output printed in JSON format.

package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/graphql-go/graphql"
)

func main() {
	// Schema
	fields := graphql.Fields{
		"hello": &graphql.Field{
			Type: graphql.String,
			Resolve: func(p graphql.ResolveParams) (any, 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”}}
}

For more complex examples, refer to the examples/ directory and graphql_test.go.

Origin and Current Direction

This project was originally a port of v0.4.3 of graphql-js (excluding the Validator), which was based on the July 2015 GraphQL specification. graphql is currently several versions behind graphql-js, however future efforts will be guided directly by the latest formal GraphQL specification (currently: October 2015).

Third Party Libraries
Name Author Description
graphql-go-handler Hafiz Ismail Middleware to handle GraphQL queries through HTTP requests.
graphql-relay-go Hafiz Ismail Lib to construct a graphql-go server supporting react-relay.
golang-relay-starter-kit Hafiz Ismail Barebones starting point for a Relay application with Golang GraphQL server.
Blog Posts
Roadmap
  • Lexer
  • Parser
  • Schema Parser
  • Printer
  • Schema Printer
  • Visitor
  • Executor
  • Validator
  • Examples
    • Basic Usage (see: PR-#21)
    • React/Relay
  • Alpha Release (v0.1)

Documentation

Index

Constants

View Source
const (
	// Operations
	DirectiveLocationQuery              = "QUERY"
	DirectiveLocationMutation           = "MUTATION"
	DirectiveLocationSubscription       = "SUBSCRIPTION"
	DirectiveLocationField              = "FIELD"
	DirectiveLocationFragmentDefinition = "FRAGMENT_DEFINITION"
	DirectiveLocationFragmentSpread     = "FRAGMENT_SPREAD"
	DirectiveLocationInlineFragment     = "INLINE_FRAGMENT"

	// Schema Definitions
	DirectiveLocationSchema               = "SCHEMA"
	DirectiveLocationScalar               = "SCALAR"
	DirectiveLocationObject               = "OBJECT"
	DirectiveLocationFieldDefinition      = "FIELD_DEFINITION"
	DirectiveLocationArgumentDefinition   = "ARGUMENT_DEFINITION"
	DirectiveLocationInterface            = "INTERFACE"
	DirectiveLocationUnion                = "UNION"
	DirectiveLocationEnum                 = "ENUM"
	DirectiveLocationEnumValue            = "ENUM_VALUE"
	DirectiveLocationInputObject          = "INPUT_OBJECT"
	DirectiveLocationInputFieldDefinition = "INPUT_FIELD_DEFINITION"
)
View Source
const (
	TypeKindScalar      = "SCALAR"
	TypeKindObject      = "OBJECT"
	TypeKindInterface   = "INTERFACE"
	TypeKindUnion       = "UNION"
	TypeKindEnum        = "ENUM"
	TypeKindInputObject = "INPUT_OBJECT"
	TypeKindList        = "LIST"
	TypeKindNonNull     = "NON_NULL"
)
View Source
const DefaultDeprecationReason = "No longer supported"

DefaultDeprecationReason Constant string used for default reason for a deprecation.

Variables

View Source
var (
	// ErrCoroutineStopped is returned from PauseCoroutine when a coroutine is stopped. The caller
	// should propagate the error up as quickly as possible.
	ErrCoroutineStopped = errors.New("graphql: coroutine stopped")
	// ErrNoCoroutine is returned from PauseCoroutine when there's no coroutine in the context.
	ErrNoCoroutine = errors.New("graphql: no coroutine")
)
View Source
var Boolean = NewScalar(ScalarConfig{
	Name:        "Boolean",
	Description: "The `Boolean` scalar type represents `true` or `false`.",
	Serialize:   coerceBool,
	ParseValue:  coerceBool,
	ParseLiteral: func(valueAST ast.Value) any {
		switch valueAST := valueAST.(type) {
		case *ast.BooleanValue:
			return valueAST.Value
		}
		return nil
	},
})

Boolean is the GraphQL boolean type definition

View Source
var DeprecatedDirective = NewDirective(DirectiveConfig{
	Name:        "deprecated",
	Description: "Marks an element of a GraphQL schema as no longer supported.",
	Args: FieldConfigArgument{
		"reason": &ArgumentConfig{
			Type: String,
			Description: "Explains why this element was deprecated, usually also including a " +
				"suggestion for how to access supported similar data. Formatted" +
				"in [Markdown](https://daringfireball.net/projects/markdown/).",
			DefaultValue: DefaultDeprecationReason,
		},
	},
	Locations: []string{
		DirectiveLocationFieldDefinition,
		DirectiveLocationEnumValue,
	},
})

DeprecatedDirective Used to declare element of a GraphQL schema as deprecated.

View Source
var DirectiveLocationEnumType = NewEnum(EnumConfig{
	Name: "__DirectiveLocation",
	Description: "A Directive can be adjacent to many parts of the GraphQL language, a " +
		"__DirectiveLocation describes one such possible adjacencies.",
	Values: EnumValueConfigMap{
		"QUERY": &EnumValueConfig{
			Value:       DirectiveLocationQuery,
			Description: "Location adjacent to a query operation.",
		},
		"MUTATION": &EnumValueConfig{
			Value:       DirectiveLocationMutation,
			Description: "Location adjacent to a mutation operation.",
		},
		"SUBSCRIPTION": &EnumValueConfig{
			Value:       DirectiveLocationSubscription,
			Description: "Location adjacent to a subscription operation.",
		},
		"FIELD": &EnumValueConfig{
			Value:       DirectiveLocationField,
			Description: "Location adjacent to a field.",
		},
		"FRAGMENT_DEFINITION": &EnumValueConfig{
			Value:       DirectiveLocationFragmentDefinition,
			Description: "Location adjacent to a fragment definition.",
		},
		"FRAGMENT_SPREAD": &EnumValueConfig{
			Value:       DirectiveLocationFragmentSpread,
			Description: "Location adjacent to a fragment spread.",
		},
		"INLINE_FRAGMENT": &EnumValueConfig{
			Value:       DirectiveLocationInlineFragment,
			Description: "Location adjacent to an inline fragment.",
		},
		"SCHEMA": &EnumValueConfig{
			Value:       DirectiveLocationSchema,
			Description: "Location adjacent to a schema definition.",
		},
		"SCALAR": &EnumValueConfig{
			Value:       DirectiveLocationScalar,
			Description: "Location adjacent to a scalar definition.",
		},
		"OBJECT": &EnumValueConfig{
			Value:       DirectiveLocationObject,
			Description: "Location adjacent to a object definition.",
		},
		"FIELD_DEFINITION": &EnumValueConfig{
			Value:       DirectiveLocationFieldDefinition,
			Description: "Location adjacent to a field definition.",
		},
		"ARGUMENT_DEFINITION": &EnumValueConfig{
			Value:       DirectiveLocationArgumentDefinition,
			Description: "Location adjacent to an argument definition.",
		},
		"INTERFACE": &EnumValueConfig{
			Value:       DirectiveLocationInterface,
			Description: "Location adjacent to an interface definition.",
		},
		"UNION": &EnumValueConfig{
			Value:       DirectiveLocationUnion,
			Description: "Location adjacent to a union definition.",
		},
		"ENUM": &EnumValueConfig{
			Value:       DirectiveLocationEnum,
			Description: "Location adjacent to an enum definition.",
		},
		"ENUM_VALUE": &EnumValueConfig{
			Value:       DirectiveLocationEnumValue,
			Description: "Location adjacent to an enum value definition.",
		},
		"INPUT_OBJECT": &EnumValueConfig{
			Value:       DirectiveLocationInputObject,
			Description: "Location adjacent to an input object type definition.",
		},
		"INPUT_FIELD_DEFINITION": &EnumValueConfig{
			Value:       DirectiveLocationInputFieldDefinition,
			Description: "Location adjacent to an input object field definition.",
		},
	},
})

DirectiveLocationEnumType is type definition for __DirectiveLocation

View Source
var DirectiveType = NewObject(ObjectConfig{
	Name: "__Directive",
	Description: "A Directive provides a way to describe alternate runtime execution and " +
		"type validation behavior in a GraphQL document. " +
		"\n\nIn some cases, you need to provide options to alter GraphQL's " +
		"execution behavior in ways field arguments will not suffice, such as " +
		"conditionally including or skipping a field. Directives provide this by " +
		"describing additional information to the executor.",
	Fields: Fields{
		"name": &Field{
			Type: NewNonNull(String),
		},
		"description": &Field{
			Type: String,
		},
		"locations": &Field{
			Type: NewNonNull(NewList(
				NewNonNull(DirectiveLocationEnumType),
			)),
		},
		"args": &Field{
			Type: NewNonNull(NewList(
				NewNonNull(InputValueType),
			)),
		},

		"onOperation": &Field{
			DeprecationReason: "Use `locations`.",
			Type:              NewNonNull(Boolean),
			Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
				if dir, ok := p.Source.(*Directive); ok {
					res := false
					for _, loc := range dir.Locations {
						if loc == DirectiveLocationQuery ||
							loc == DirectiveLocationMutation ||
							loc == DirectiveLocationSubscription {
							res = true
							break
						}
					}
					return res, nil
				}
				return false, nil
			},
		},
		"onFragment": &Field{
			DeprecationReason: "Use `locations`.",
			Type:              NewNonNull(Boolean),
			Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
				if dir, ok := p.Source.(*Directive); ok {
					res := false
					for _, loc := range dir.Locations {
						if loc == DirectiveLocationFragmentSpread ||
							loc == DirectiveLocationInlineFragment ||
							loc == DirectiveLocationFragmentDefinition {
							res = true
							break
						}
					}
					return res, nil
				}
				return false, nil
			},
		},
		"onField": &Field{
			DeprecationReason: "Use `locations`.",
			Type:              NewNonNull(Boolean),
			Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
				if dir, ok := p.Source.(*Directive); ok {
					res := false
					for _, loc := range dir.Locations {
						if loc == DirectiveLocationField {
							res = true
							break
						}
					}
					return res, nil
				}
				return false, nil
			},
		},
	},
})

DirectiveType is type definition for __Directive

View Source
var EnumValueType = NewObject(ObjectConfig{
	Name: "__EnumValue",
	Description: "One possible value for a given Enum. Enum values are unique values, not " +
		"a placeholder for a string or numeric value. However an Enum value is " +
		"returned in a JSON response as a string.",
	Fields: Fields{
		"name": &Field{
			Type: NewNonNull(String),
		},
		"description": &Field{
			Type: String,
		},
		"isDeprecated": &Field{
			Type: NewNonNull(Boolean),
			Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
				if field, ok := p.Source.(*EnumValueDefinition); ok {
					return field.DeprecationReason != "", nil
				}
				return false, nil
			},
		},
		"deprecationReason": &Field{
			Type: String,
		},
	},
})

EnumValueType is type definition for __EnumValue

View Source
var FieldType = NewObject(ObjectConfig{
	Name: "__Field",
	Description: "Object and Interface types are described by a list of Fields, each of " +
		"which has a name, potentially a list of arguments, and a return type.",
	Fields: Fields{
		"name": &Field{
			Type: NewNonNull(String),
		},
		"description": &Field{
			Type: String,
		},
		"args": &Field{
			Type: NewNonNull(NewList(NewNonNull(InputValueType))),
			Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
				if field, ok := p.Source.(*FieldDefinition); ok {
					args := append([]*Argument(nil), field.Args...)
					sort.Slice(args, func(i, j int) bool {
						return args[i].Name() < args[j].Name()
					})
					return args, nil
				}
				return []any{}, nil
			},
		},
		"type": &Field{
			Type: NewNonNull(TypeType),
		},
		"isDeprecated": &Field{
			Type: NewNonNull(Boolean),
			Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
				if field, ok := p.Source.(*FieldDefinition); ok {
					return field.DeprecationReason != "", nil
				}
				return false, nil
			},
		},
		"deprecationReason": &Field{
			Type: String,
		},
	},
})

FieldType is type definition for __Field

View Source
var Float = NewScalar(ScalarConfig{
	Name: "Float",
	Description: "The `Float` scalar type represents signed double-precision fractional " +
		"values as specified by " +
		"[IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). ",
	Serialize:  coerceFloat64,
	ParseValue: coerceFloat64,
	ParseLiteral: func(valueAST ast.Value) any {
		switch valueAST := valueAST.(type) {
		case *ast.FloatValue:
			if floatValue, err := strconv.ParseFloat(valueAST.Value, 64); err == nil {
				return floatValue
			}
		case *ast.IntValue:
			if floatValue, err := strconv.ParseFloat(valueAST.Value, 64); err == nil {
				return floatValue
			}
		}
		return nil
	},
})

Float is the GraphQL float type definition.

View Source
var ID = NewScalar(ScalarConfig{
	Name: "ID",
	Description: "The `ID` scalar type represents a unique identifier, often used to " +
		"refetch an object or as key for a cache. The ID type appears in a JSON " +
		"response as a String; however, it is not intended to be human-readable. " +
		"When expected as an input type, any string (such as `\"4\"`) or integer " +
		"(such as `4`) input value will be accepted as an ID.",
	Serialize:  coerceString,
	ParseValue: coerceString,
	ParseLiteral: func(valueAST ast.Value) any {
		switch valueAST := valueAST.(type) {
		case *ast.IntValue:
			return valueAST.Value
		case *ast.StringValue:
			return valueAST.Value
		}
		return nil
	},
})

ID is the GraphQL id type definition

View Source
var IncludeDirective = NewDirective(DirectiveConfig{
	Name: "include",
	Description: "Directs the executor to include this field or fragment only when " +
		"the `if` argument is true.",
	Locations: []string{
		DirectiveLocationField,
		DirectiveLocationFragmentSpread,
		DirectiveLocationInlineFragment,
	},
	Args: FieldConfigArgument{
		"if": &ArgumentConfig{
			Type:        NewNonNull(Boolean),
			Description: "Included when true.",
		},
	},
})

IncludeDirective is used to conditionally include fields or fragments.

View Source
var InputValueType = NewObject(ObjectConfig{
	Name: "__InputValue",
	Description: "Arguments provided to Fields or Directives and the input fields of an " +
		"InputObject are represented as Input Values which describe their type " +
		"and optionally a default value.",
	Fields: Fields{
		"name": &Field{
			Type: NewNonNull(String),
		},
		"description": &Field{
			Type: String,
		},
		"type": &Field{
			Type: NewNonNull(TypeType),
		},
		"defaultValue": &Field{
			Type: String,
			Description: "A GraphQL-formatted string representing the default value for this " +
				"input value.",
			Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
				if inputVal, ok := p.Source.(*Argument); ok {
					if inputVal.DefaultValue == nil {
						return nil, nil
					}
					if isNullish(inputVal.DefaultValue) {
						return nil, nil
					}
					astVal := astFromValue(inputVal.DefaultValue, inputVal)
					return printer.Print(astVal), nil
				}
				if inputVal, ok := p.Source.(*InputObjectField); ok {
					if inputVal.DefaultValue == nil {
						return nil, nil
					}
					astVal := astFromValue(inputVal.DefaultValue, inputVal)
					return printer.Print(astVal), nil
				}
				return nil, nil
			},
		},
	},
})

InputValueType is type definition for __InputValue

View Source
var Int = NewScalar(ScalarConfig{
	Name: "Int",
	Description: "The `Int` scalar type represents non-fractional signed whole numeric " +
		"values. Int can represent values between -(2^31) and 2^31 - 1. ",
	Serialize:  coerceInt,
	ParseValue: coerceInt,
	ParseLiteral: func(valueAST ast.Value) any {
		switch valueAST := valueAST.(type) {
		case *ast.IntValue:
			if intValue, err := strconv.Atoi(valueAST.Value); err == nil {
				return intValue
			}
		}
		return nil
	},
})

Int is the GraphQL Integer type definition.

View Source
var NameRegExp = regexp.MustCompile("^[_a-zA-Z][_a-zA-Z0-9]*$")
View Source
var SchemaMetaFieldDef = &FieldDefinition{
	Name:        "__schema",
	Type:        NewNonNull(SchemaType),
	Description: "Access the current type schema of this server.",
	Args:        []*Argument{},
	Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
		return p.Info.Schema, nil
	},
}

SchemaMetaFieldDef Meta field definition for Schema

View Source
var SchemaType = NewObject(ObjectConfig{
	Name: "__Schema",
	Description: `A GraphQL Schema defines the capabilities of a GraphQL server. ` +
		`It exposes all available types and directives on the server, as well as ` +
		`the entry points for query, mutation, and subscription operations.`,
	Fields: Fields{
		"types": &Field{
			Description: "A list of all types supported by this server.",
			Type: NewNonNull(NewList(
				NewNonNull(TypeType),
			)),
			Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
				if schema, ok := p.Source.(Schema); ok {
					var results []Type
					for _, ttype := range schema.TypeMap() {
						results = append(results, ttype)
					}
					sort.Slice(results, func(i, j int) bool {
						return results[i].Name() < results[j].Name()
					})
					return results, nil
				}
				return []Type{}, nil
			},
		},
		"queryType": &Field{
			Description: "The type that query operations will be rooted at.",
			Type:        NewNonNull(TypeType),
			Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
				if schema, ok := p.Source.(Schema); ok {
					return schema.QueryType(), nil
				}
				return nil, nil
			},
		},
		"mutationType": &Field{
			Description: `If this server supports mutation, the type that ` +
				`mutation operations will be rooted at.`,
			Type: TypeType,
			Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
				if schema, ok := p.Source.(Schema); ok {
					if schema.MutationType() != nil {
						return schema.MutationType(), nil
					}
				}
				return nil, nil
			},
		},
		"subscriptionType": &Field{
			Description: `If this server supports subscription, the type that ` +
				`subscription operations will be rooted at.`,
			Type: TypeType,
			Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
				if schema, ok := p.Source.(Schema); ok {
					if schema.SubscriptionType() != nil {
						return schema.SubscriptionType(), nil
					}
				}
				return nil, nil
			},
		},
		"directives": &Field{
			Description: `A list of all directives supported by this server.`,
			Type: NewNonNull(NewList(
				NewNonNull(DirectiveType),
			)),
			Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
				if schema, ok := p.Source.(Schema); ok {
					return schema.Directives(), nil
				}
				return nil, nil
			},
		},
	},
})

SchemaType is type definition for __Schema

View Source
var SkipDirective = NewDirective(DirectiveConfig{
	Name: "skip",
	Description: "Directs the executor to skip this field or fragment when the `if` " +
		"argument is true.",
	Args: FieldConfigArgument{
		"if": &ArgumentConfig{
			Type:        NewNonNull(Boolean),
			Description: "Skipped when true.",
		},
	},
	Locations: []string{
		DirectiveLocationField,
		DirectiveLocationFragmentSpread,
		DirectiveLocationInlineFragment,
	},
})

SkipDirective Used to conditionally skip (exclude) fields or fragments.

SpecifiedDirectives is the full list of specified directives.

SpecifiedRules set includes all validation rules defined by the GraphQL spec.

View Source
var String = NewScalar(ScalarConfig{
	Name: "String",
	Description: "The `String` scalar type represents textual data, represented as UTF-8 " +
		"character sequences. The String type is most often used by GraphQL to " +
		"represent free-form human-readable text.",
	Serialize:  coerceString,
	ParseValue: coerceString,
	ParseLiteral: func(valueAST ast.Value) any {
		switch valueAST := valueAST.(type) {
		case *ast.StringValue:
			return valueAST.Value
		}
		return nil
	},
})

String is the GraphQL string type definition

View Source
var TypeKindEnumType = NewEnum(EnumConfig{
	Name:        "__TypeKind",
	Description: "An enum describing what kind of type a given `__Type` is",
	Values: EnumValueConfigMap{
		"SCALAR": &EnumValueConfig{
			Value:       TypeKindScalar,
			Description: "Indicates this type is a scalar.",
		},
		"OBJECT": &EnumValueConfig{
			Value: TypeKindObject,
			Description: "Indicates this type is an object. " +
				"`fields` and `interfaces` are valid fields.",
		},
		"INTERFACE": &EnumValueConfig{
			Value: TypeKindInterface,
			Description: "Indicates this type is an interface. " +
				"`fields` and `possibleTypes` are valid fields.",
		},
		"UNION": &EnumValueConfig{
			Value: TypeKindUnion,
			Description: "Indicates this type is a union. " +
				"`possibleTypes` is a valid field.",
		},
		"ENUM": &EnumValueConfig{
			Value: TypeKindEnum,
			Description: "Indicates this type is an enum. " +
				"`enumValues` is a valid field.",
		},
		"INPUT_OBJECT": &EnumValueConfig{
			Value: TypeKindInputObject,
			Description: "Indicates this type is an input object. " +
				"`inputFields` is a valid field.",
		},
		"LIST": &EnumValueConfig{
			Value: TypeKindList,
			Description: "Indicates this type is a list. " +
				"`ofType` is a valid field.",
		},
		"NON_NULL": &EnumValueConfig{
			Value: TypeKindNonNull,
			Description: "Indicates this type is a non-null. " +
				"`ofType` is a valid field.",
		},
	},
})

TypeKindEnumType is type definition for __TypeKind

View Source
var TypeMetaFieldDef = &FieldDefinition{
	Name:        "__type",
	Type:        TypeType,
	Description: "Request the type information of a single type.",
	Args: []*Argument{
		{
			PrivateName: "name",
			Type:        NewNonNull(String),
		},
	},
	Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
		name, ok := p.Args["name"].(string)
		if !ok {
			return nil, nil
		}
		return p.Info.Schema.Type(name), nil
	},
}

TypeMetaFieldDef Meta field definition for types

View Source
var TypeNameMetaFieldDef = &FieldDefinition{
	Name:        "__typename",
	Type:        NewNonNull(String),
	Description: "The name of the current Object type at runtime.",
	Args:        []*Argument{},
	Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
		return p.Info.ParentType.Name(), nil
	},
}

TypeNameMetaFieldDef Meta field definition for type names

View Source
var TypeType = NewObject(ObjectConfig{
	Name: "__Type",
	Description: "The fundamental unit of any GraphQL Schema is the type. There are " +
		"many kinds of types in GraphQL as represented by the `__TypeKind` enum." +
		"\n\nDepending on the kind of a type, certain fields describe " +
		"information about that type. Scalar types provide no information " +
		"beyond a name and description, while Enum types provide their values. " +
		"Object and Interface types provide the fields they describe. Abstract " +
		"types, Union and Interface, provide the Object types possible " +
		"at runtime. List and NonNull types compose other types.",

	Fields: Fields{
		"kind": &Field{
			Type: NewNonNull(TypeKindEnumType),
			Resolve: func(ctx context.Context, p ResolveParams) (any, error) {
				switch p.Source.(type) {
				case *Scalar:
					return TypeKindScalar, nil
				case *Object:
					return TypeKindObject, nil
				case *Interface:
					return TypeKindInterface, nil
				case *Union:
					return TypeKindUnion, nil
				case *Enum:
					return TypeKindEnum, nil
				case *InputObject:
					return TypeKindInputObject, nil
				case *List:
					return TypeKindList, nil
				case *NonNull:
					return TypeKindNonNull, nil
				}
				return nil, fmt.Errorf("graphql: unknown kind of type: %v", p.Source)
			},
		},
		"name": &Field{
			Type: String,
		},
		"description": &Field{
			Type: String,
		},
		"fields":        &Field{},
		"interfaces":    &Field{},
		"possibleTypes": &Field{},
		"enumValues":    &Field{},
		"inputFields":   &Field{},
		"ofType":        &Field{},
	},
})

TypeType is type definition for __Type

Functions

func CycleErrorMessage

func CycleErrorMessage(fragName string, spreadNames []string) string

func DisconnectCoroutine

func DisconnectCoroutine(ctx context.Context) context.Context

DisconnectCoroutine removes any coroutine from the context. This should be used when passing the context to a goroutine that runs concurrently with other code that may use the coroutine.

func FieldASTsToNodeASTs

func FieldASTsToNodeASTs(fieldASTs []*ast.Field) []ast.Node

func HasCoroutine

func HasCoroutine(ctx context.Context) bool

HasCoroutine returns true if the context contains a coroutine.

func IsAbstractType

func IsAbstractType(ttype any) bool

func IsCompositeType

func IsCompositeType(ttype any) bool

IsCompositeType determines if given type is a GraphQLComposite type

func IsInputType

func IsInputType(ttype Type) bool

IsInputType determines if given type is a GraphQLInputType

func IsLeafType

func IsLeafType(ttype Type) bool

IsLeafType determines if given type is a leaf value

func IsOutputType

func IsOutputType(ttype Type) bool

IsOutputType determines if given type is a GraphQLOutputType

func MisplaceDirectiveMessage

func MisplaceDirectiveMessage(directiveName, location string) string

func NewLocatedError

func NewLocatedError(err any, nodes []ast.Node) *gqlerrors.Error

func PauseCoroutine

func PauseCoroutine(ctx context.Context) error

PauseCoroutine is called inside a coroutine and pauses execution returning control the parent. It returns ErrNoCoroutine when there's no coroutine in the context and ErrCoroutineStopped if the coroutine is stopped.

func RequestTypeNames

func RequestTypeNames(doc *ast.Document)

RequestTypeNames rewrites an ast document to include __typename in all selection sets.

func UndefinedFieldMessage

func UndefinedFieldMessage(fieldName string, ttypeName string, suggestedTypeNames []string, suggestedFieldNames []string) string

func UndefinedVarMessage

func UndefinedVarMessage(varName string, opName string) string

func UnusedVariableMessage

func UnusedVariableMessage(varName string, opName string) string

func VisitUsingRules

func VisitUsingRules(schema *Schema, typeInfo *TypeInfo, astDoc *ast.Document, rules []ValidationRuleFn) []gqlerrors.FormattedError

VisitUsingRules This uses a specialized visitor which runs multiple visitors in parallel, while maintaining the visitor skip and break API.

@internal Had to expose it to unit test experimental customizable validation feature, but not meant for public consumption

Types

type Abstract

type Abstract interface {
	Name() string
}

Abstract interface for types that may describe the parent context of a selection set.

type Argument

type Argument struct {
	PrivateName        string `json:"name"`
	Type               Input  `json:"type"`
	DefaultValue       any    `json:"defaultValue"`
	PrivateDescription string `json:"description"`
}

func (*Argument) Description

func (st *Argument) Description() string

func (*Argument) Error

func (st *Argument) Error() error

func (*Argument) Name

func (st *Argument) Name() string

func (*Argument) String

func (st *Argument) String() string

type ArgumentConfig

type ArgumentConfig struct {
	Type         Input  `json:"type"`
	DefaultValue any    `json:"defaultValue"`
	Description  string `json:"description"`
}

type BuildExecutionCtxParams

type BuildExecutionCtxParams struct {
	Schema            Schema
	Root              any
	AST               *ast.Document
	OperationName     string
	Args              map[string]any
	Errors            []gqlerrors.FormattedError
	Result            *Result
	DeprecatedFieldFn func(context.Context, *Object, *FieldDefinition) error
	// TODO: Abstract this to possibly handle more types
	FieldDefinitionDirectiveHandler func(context.Context, *ast.Directive, *FieldDefinition) error
	DisallowIntrospection           bool
	Tracer                          Tracer
	EnableCoroutines                bool
}

type CollectFieldsParams

type CollectFieldsParams struct {
	ExeContext           *ExecutionContext
	RuntimeType          *Object // previously known as OperationType
	SelectionSet         *ast.SelectionSet
	Fields               map[string][]*ast.Field
	VisitedFragmentNames map[string]struct{}
}

type Composite

type Composite interface {
	Name() string
	Description() string
	String() string
	Error() error
}

Composite interface for types that may describe the parent context of a selection set.

type CountingTracer

type CountingTracer struct {
	// contains filtered or unexported fields
}

func NewCountingTracer

func NewCountingTracer(unique bool) *CountingTracer

NewCountingTracer returns a new counting tracer. Unique if true aggregates traces for the same path. Otherwise, only consecutive traces for the same path are aggregated.

func (*CountingTracer) IterTraces

func (t *CountingTracer) IterTraces() iter.Seq2[int, *TracePathCount]

IterTraces returns an iterator of gathered traces. DO NOT retain any of the traces at the time Recycle is called on the tracer.

func (*CountingTracer) Recycle

func (t *CountingTracer) Recycle()

Recycle returns the counting tracer and all traces to the pool.

func (*CountingTracer) Trace

func (t *CountingTracer) Trace(ctx context.Context, path []string, duration time.Duration)

type Directive

type Directive struct {
	Name        string      `json:"name"`
	Description string      `json:"description"`
	Locations   []string    `json:"locations"`
	Args        []*Argument `json:"args"`
	// contains filtered or unexported fields
}

Directive structs are used by the GraphQL runtime as a way of modifying execution behavior. Type system creators will usually not create these directly.

func NewDirective

func NewDirective(config DirectiveConfig) *Directive

type DirectiveConfig

type DirectiveConfig struct {
	Name        string              `json:"name"`
	Description string              `json:"description"`
	Locations   []string            `json:"locations"`
	Args        FieldConfigArgument `json:"args"`
}

DirectiveConfig options for creating a new GraphQLDirective

type Enum

type Enum struct {
	PrivateName        string `json:"name"`
	PrivateDescription string `json:"description"`
	// contains filtered or unexported fields
}

func NewEnum

func NewEnum(config EnumConfig) *Enum

func (*Enum) Description

func (gt *Enum) Description() string

func (*Enum) Error

func (gt *Enum) Error() error

func (*Enum) Name

func (gt *Enum) Name() string

func (*Enum) ParseLiteral

func (gt *Enum) ParseLiteral(valueAST ast.Value) any

func (*Enum) ParseValue

func (gt *Enum) ParseValue(value any) any

func (*Enum) Serialize

func (gt *Enum) Serialize(value any) any

func (*Enum) String

func (gt *Enum) String() string

func (*Enum) Values

func (gt *Enum) Values() []*EnumValueDefinition

type EnumConfig

type EnumConfig struct {
	Name        string             `json:"name"`
	Values      EnumValueConfigMap `json:"values"`
	Description string             `json:"description"`
}

type EnumValueConfig

type EnumValueConfig struct {
	Value             any    `json:"value"`
	DeprecationReason string `json:"deprecationReason,omitempty"`
	Description       string `json:"description"`
}

type EnumValueConfigMap

type EnumValueConfigMap map[string]*EnumValueConfig

type EnumValueDefinition

type EnumValueDefinition struct {
	Name              string `json:"name"`
	Value             any    `json:"value"`
	DeprecationReason string `json:"deprecationReason,omitempty"`
	Description       string `json:"description"`
}

type ExecuteFieldsParams

type ExecuteFieldsParams struct {
	ExecutionContext *ExecutionContext
	ParentType       *Object
	Source           any
	Fields           map[string][]*ast.Field
}

type ExecuteOperationParams

type ExecuteOperationParams struct {
	ExecutionContext *ExecutionContext
	Root             any
	Operation        ast.Definition
}

type ExecuteParams

type ExecuteParams struct {
	Schema            Schema
	Root              any
	AST               *ast.Document
	OperationName     string
	Args              map[string]any
	DeprecatedFieldFn func(ctx context.Context, parent *Object, fieldDef *FieldDefinition) error
	// TODO: Abstract this to possibly handle more types
	FieldDefinitionDirectiveHandler func(context.Context, *ast.Directive, *FieldDefinition) error
	DisallowIntrospection           bool
	EnableCoroutines                bool
	// TimeoutWait is the amount of time to allow for resolvers to handle
	// a context deadline error before the executor does.
	TimeoutWait time.Duration
	Tracer      Tracer
}

type ExecutionContext

type ExecutionContext struct {
	Schema            Schema
	Fragments         map[string]*ast.FragmentDefinition
	Root              any
	Operation         ast.Definition
	VariableValues    map[string]any
	Errors            []gqlerrors.FormattedError
	DeprecatedFieldFn func(context.Context, *Object, *FieldDefinition) error
	// TODO: Abstract this to possibly handle more types
	FieldDefinitionDirectiveHandler func(context.Context, *ast.Directive, *FieldDefinition) error
	DisallowIntrospection           bool
	Tracer                          Tracer
	EnableCoroutines                bool
	// contains filtered or unexported fields
}

type Field

type Field struct {
	Name              string              `json:"name"` // used by graphlql-relay
	Type              Output              `json:"type"`
	Args              FieldConfigArgument `json:"args"`
	Resolve           FieldResolveFn
	DeprecationReason string           `json:"deprecationReason,omitempty"`
	Description       string           `json:"description"`
	Directives        []*ast.Directive `json:"directives,omitempty"`
}

type FieldArgument

type FieldArgument struct {
	Name         string `json:"name"`
	Type         Type   `json:"type"`
	DefaultValue any    `json:"defaultValue"`
	Description  string `json:"description"`
}

type FieldConfigArgument

type FieldConfigArgument map[string]*ArgumentConfig

type FieldDefinition

type FieldDefinition struct {
	Name              string           `json:"name"`
	Description       string           `json:"description"`
	Type              Output           `json:"type"`
	Args              []*Argument      `json:"args"`
	Resolve           FieldResolveFn   `json:"-"`
	DeprecationReason string           `json:"deprecationReason,omitempty"`
	Directives        []*ast.Directive `json:"directives,omitempty"`
}

func DefaultTypeInfoFieldDef

func DefaultTypeInfoFieldDef(schema *Schema, parentType Type, fieldAST *ast.Field) *FieldDefinition

DefaultTypeInfoFieldDef Not exactly the same as the executor's definition of FieldDef, in this statically evaluated environment we do not always have an Object type, and need to handle Interface and Union types.

type FieldDefinitionMap

type FieldDefinitionMap map[string]*FieldDefinition

type FieldResolveFn

type FieldResolveFn func(ctx context.Context, p ResolveParams) (any, error)

type Fields

type Fields map[string]*Field

type FieldsThunk

type FieldsThunk func() Fields

type HasSelectionSet

type HasSelectionSet interface {
	GetLoc() ast.Location
	GetSelectionSet() *ast.SelectionSet
}

type Input

type Input interface {
	Name() string
	Description() string
	String() string
	Error() error
}

Input interface for types that may be used as input types for arguments and directives.

type InputObject

type InputObject struct {
	PrivateName        string `json:"name"`
	PrivateDescription string `json:"description"`
	// contains filtered or unexported fields
}

InputObject Type Definition

An input object defines a structured collection of fields which may be supplied to a field argument.

Using `NonNull` will ensure that a value must be provided by the query

Example:

var GeoPoint = new InputObject({
  name: 'GeoPoint',
  fields: {
    lat: { type: new NonNull(Float) },
    lon: { type: new NonNull(Float) },
    alt: { type: Float, defaultValue: 0 },
  }
});

func NewInputObject

func NewInputObject(config InputObjectConfig) *InputObject

func (*InputObject) AddInputField

func (gt *InputObject) AddInputField(fieldName string, fieldConfig *InputObjectFieldConfig)

func (*InputObject) Description

func (gt *InputObject) Description() string

func (*InputObject) Error

func (gt *InputObject) Error() error

func (*InputObject) Fields

func (gt *InputObject) Fields() InputObjectFieldMap

func (*InputObject) Name

func (gt *InputObject) Name() string

func (*InputObject) String

func (gt *InputObject) String() string

type InputObjectConfig

type InputObjectConfig struct {
	Name        string `json:"name"`
	Fields      any    `json:"fields"`
	Description string `json:"description"`
}

type InputObjectConfigFieldMap

type InputObjectConfigFieldMap map[string]*InputObjectFieldConfig

type InputObjectConfigFieldMapThunk

type InputObjectConfigFieldMapThunk func() InputObjectConfigFieldMap

type InputObjectField

type InputObjectField struct {
	PrivateName        string `json:"name"`
	Type               Input  `json:"type"`
	DefaultValue       any    `json:"defaultValue"`
	PrivateDescription string `json:"description"`
	DeprecationReason  string `json:"deprecationReason,omitempty"`
}

func (*InputObjectField) Description

func (st *InputObjectField) Description() string

func (*InputObjectField) Error

func (st *InputObjectField) Error() error

func (*InputObjectField) Name

func (st *InputObjectField) Name() string

func (*InputObjectField) String

func (st *InputObjectField) String() string

type InputObjectFieldConfig

type InputObjectFieldConfig struct {
	Type              Input  `json:"type"`
	DefaultValue      any    `json:"defaultValue"`
	DeprecationReason string `json:"deprecationReason,omitempty"`
	Description       string `json:"description"`
}

type InputObjectFieldMap

type InputObjectFieldMap map[string]*InputObjectField

type InputObjectFields

type InputObjectFields map[string]*InputObjectField

type Interface

type Interface struct {
	PrivateName        string `json:"name"`
	PrivateDescription string `json:"description"`
	ResolveType        ResolveTypeFn
	// contains filtered or unexported fields
}

Interface Type Definition

When a field can return one of a heterogeneous set of types, a Interface type is used to describe what types are possible, what fields are in common across all types, as well as a function to determine which type is actually used when the field is resolved.

Example:

var EntityType = new Interface({
  name: 'Entity',
  fields: {
    name: { type: String }
  }
});

func NewInterface

func NewInterface(config InterfaceConfig) *Interface

func (*Interface) AddFieldConfig

func (it *Interface) AddFieldConfig(fieldName string, fieldConfig *Field)

func (*Interface) Description

func (it *Interface) Description() string

func (*Interface) Error

func (it *Interface) Error() error

func (*Interface) Fields

func (it *Interface) Fields() FieldDefinitionMap

func (*Interface) Name

func (it *Interface) Name() string

func (*Interface) String

func (it *Interface) String() string

type InterfaceConfig

type InterfaceConfig struct {
	Name        string `json:"name"`
	Fields      any    `json:"fields"`
	ResolveType ResolveTypeFn
	Description string `json:"description"`
}

type InterfacesThunk

type InterfacesThunk func() []*Interface

type IsTypeOfFn

type IsTypeOfFn func(p IsTypeOfParams) bool

type IsTypeOfParams

type IsTypeOfParams struct {
	// Value that needs to be resolve.
	// Use this to decide which GraphQLObject this value maps to.
	Value any

	// Info is a collection of information about the current execution state.
	Info ResolveInfo
}

IsTypeOfParams Params for IsTypeOfFn()

type Leaf

type Leaf interface {
	Name() string
	Description() string
	String() string
	Error() error
	Serialize(value any) any
}

Leaf interface for types that may be leaf values

type List

type List struct {
	OfType Type `json:"ofType"`
	// contains filtered or unexported fields
}

List Modifier

A list is a kind of type marker, a wrapping type which points to another type. Lists are often created within the context of defining the fields of an object type.

Example:

var PersonType = new Object({
  name: 'Person',
  fields: () => ({
    parents: { type: new List(Person) },
    children: { type: new List(Person) },
  })
})

func NewList

func NewList(ofType Type) *List

func (*List) Description

func (gl *List) Description() string

func (*List) Error

func (gl *List) Error() error

func (*List) Name

func (gl *List) Name() string

func (*List) String

func (gl *List) String() string

type Named

type Named interface {
	String() string
}

Named interface for types that do not include modifiers like List or NonNull.

func GetNamed

func GetNamed(ttype Type) Named

GetNamed returns the Named type of the given GraphQL type

type NonNull

type NonNull struct {
	OfType Type `json:"ofType"`
	// contains filtered or unexported fields
}

NonNull Modifier

A non-null is a kind of type marker, a wrapping type which points to another type. Non-null types enforce that their values are never null and can ensure an error is raised if this ever occurs during a request. It is useful for fields which you can make a strong guarantee on non-nullability, for example usually the id field of a database row will never be null.

Example:

var RowType = new Object({
  name: 'Row',
  fields: () => ({
    id: { type: new NonNull(String) },
  })
})

Note: the enforcement of non-nullability occurs within the executor.

func NewNonNull

func NewNonNull(ofType Type) *NonNull

func (*NonNull) Description

func (gl *NonNull) Description() string

func (*NonNull) Error

func (gl *NonNull) Error() error

func (*NonNull) Name

func (gl *NonNull) Name() string

func (*NonNull) String

func (gl *NonNull) String() string

type Nullable

type Nullable interface {
}

Nullable interface for types that can accept null as a value.

func GetNullable

func GetNullable(ttype Type) Nullable

GetNullable returns the Nullable type of the given GraphQL type

type Object

type Object struct {
	PrivateName        string `json:"name"`
	PrivateDescription string `json:"description"`
	IsTypeOf           IsTypeOfFn
	// contains filtered or unexported fields
}

Object Type Definition

Almost all of the GraphQL types you define will be object Object types have a name, but most importantly describe their fields. Example:

var AddressType = new Object({
  name: 'Address',
  fields: {
    street: { type: String },
    number: { type: Int },
    formatted: {
      type: String,
      resolve(obj) {
        return obj.number + ' ' + obj.street
      }
    }
  }
});

When two types need to refer to each other, or a type needs to refer to itself in a field, you can use a function expression (aka a closure or a thunk) to supply the fields lazily.

Example:

var PersonType = new Object({
  name: 'Person',
  fields: () => ({
    name: { type: String },
    bestFriend: { type: PersonType },
  })
});

/

func NewObject

func NewObject(config ObjectConfig) *Object

func (*Object) AddFieldConfig

func (gt *Object) AddFieldConfig(fieldName string, fieldConfig *Field)

func (*Object) Description

func (gt *Object) Description() string

func (*Object) Error

func (gt *Object) Error() error

func (*Object) Fields

func (gt *Object) Fields() FieldDefinitionMap

func (*Object) Interfaces

func (gt *Object) Interfaces() []*Interface

func (*Object) Name

func (gt *Object) Name() string

func (*Object) String

func (gt *Object) String() string

type ObjectConfig

type ObjectConfig struct {
	Name        string     `json:"name"`
	Interfaces  any        `json:"interfaces"`
	Fields      any        `json:"fields"`
	IsTypeOf    IsTypeOfFn `json:"isTypeOf"`
	Description string     `json:"description"`
}

type Output

type Output interface {
	Name() string
	Description() string
	String() string
	Error() error
}

Output interface for types that may be used as output types as the result of fields.

type Params

type Params struct {
	// Schema is the GraphQL type system to use when validating and executing a query.
	Schema Schema

	// RequestString is a GraphQL language formatted string representing the requested operation.
	RequestString string

	// RootObject is the value provided as the first argument to resolver functions on the top
	// level type (e.g. the query object type).
	RootObject map[string]any

	// VariableValues is a mapping of variable name to runtime value to use for all variables
	// defined in the requestString.
	VariableValues map[string]any

	// OperationName is the name of the operation to use if requestString contains multiple
	// possible operations. Can be omitted if requestString contains only
	// one operation.
	OperationName string

	// Tracer if set is called after each invocation of a custom resolver with the duration.
	Tracer Tracer
}

type ParseLiteralFn

type ParseLiteralFn func(valueAST ast.Value) any

ParseLiteralFn is a function type for parsing the literal value of a GraphQLScalar type

type ParseValueFn

type ParseValueFn func(value any) any

ParseValueFn is a function type for parsing the value of a GraphQLScalar type

type ResolveInfo

type ResolveInfo struct {
	FieldName      string
	FieldASTs      []*ast.Field
	ReturnType     Output
	ParentType     Composite
	Schema         Schema
	Fragments      map[string]*ast.FragmentDefinition
	RootValue      any
	Operation      ast.Definition
	VariableValues map[string]any
}

type ResolveParams

type ResolveParams struct {
	// Source is the source value
	Source any

	// Args is a map of arguments for current GraphQL request
	Args map[string]any

	// Info is a collection of information about the current execution state.
	Info ResolveInfo
}

ResolveParams Params for FieldResolveFn()

type ResolveTypeFn

type ResolveTypeFn func(ctx context.Context, p ResolveTypeParams) *Object

type ResolveTypeParams

type ResolveTypeParams struct {
	// Value that needs to be resolve.
	// Use this to decide which GraphQLObject this value maps to.
	Value any

	// Info is a collection of information about the current execution state.
	Info ResolveInfo
}

ResolveTypeParams Params for ResolveTypeFn()

type Result

type Result struct {
	Data   any                        `json:"data"`
	Errors []gqlerrors.FormattedError `json:"errors,omitempty"`
}

func Do

func Do(ctx context.Context, p Params) *Result

func Execute

func Execute(ctx context.Context, p ExecuteParams) *Result

func (*Result) HasErrors

func (r *Result) HasErrors() bool

type Scalar

type Scalar struct {
	PrivateName        string `json:"name"`
	PrivateDescription string `json:"description"`
	// contains filtered or unexported fields
}

Scalar Type Definition

The leaf values of any request and input values to arguments are Scalars (or Enums) and are defined with a name and a series of functions used to parse input from ast or variables and to ensure validity.

Example:

var OddType = new Scalar({
  name: 'Odd',
  serialize(value) {
    return value % 2 === 1 ? value : null;
  }
});

func NewScalar

func NewScalar(config ScalarConfig) *Scalar

NewScalar creates a new GraphQLScalar

func (*Scalar) Description

func (st *Scalar) Description() string

func (*Scalar) Error

func (st *Scalar) Error() error

func (*Scalar) Name

func (st *Scalar) Name() string

func (*Scalar) ParseLiteral

func (st *Scalar) ParseLiteral(valueAST ast.Value) any

func (*Scalar) ParseValue

func (st *Scalar) ParseValue(value any) any

func (*Scalar) Serialize

func (st *Scalar) Serialize(value any) any

func (*Scalar) String

func (st *Scalar) String() string

type ScalarConfig

type ScalarConfig struct {
	Name         string `json:"name"`
	Description  string `json:"description"`
	Serialize    SerializeFn
	ParseValue   ParseValueFn
	ParseLiteral ParseLiteralFn
}

ScalarConfig options for creating a new GraphQLScalar

type Schema

type Schema struct {
	// contains filtered or unexported fields
}

Schema Definition A Schema is created by supplying the root types of each type of operation, query, mutation (optional) and subscription (optional). A schema definition is then supplied to the validator and executor. Example:

myAppSchema, err := NewSchema(SchemaConfig({
  Query: MyAppQueryRootType,
  Mutation: MyAppMutationRootType,
  Subscription: MyAppSubscriptionRootType,
});

Note: If an array of `directives` are provided to GraphQLSchema, that will be the exact list of directives represented and allowed. If `directives` is not provided then a default set of the specified directives (e.g. @include and @skip) will be used. If you wish to provide *additional* directives to these specified directives, you must explicitly declare them. Example:

const MyAppSchema = new GraphQLSchema({
  ...
  directives: specifiedDirectives.concat([ myCustomDirective ]),
})

func NewSchema

func NewSchema(config SchemaConfig) (Schema, error)

func (*Schema) Directive

func (gq *Schema) Directive(name string) *Directive

func (*Schema) Directives

func (gq *Schema) Directives() []*Directive

func (*Schema) IsPossibleType

func (gq *Schema) IsPossibleType(abstractType Abstract, possibleType *Object) bool

func (*Schema) MutationType

func (gq *Schema) MutationType() *Object

func (*Schema) PossibleTypes

func (gq *Schema) PossibleTypes(abstractType Abstract) []*Object

func (*Schema) QueryType

func (gq *Schema) QueryType() *Object

func (*Schema) SubscriptionType

func (gq *Schema) SubscriptionType() *Object

func (*Schema) Type

func (gq *Schema) Type(name string) Type

func (*Schema) TypeMap

func (gq *Schema) TypeMap() TypeMap

type SchemaConfig

type SchemaConfig struct {
	Query        *Object
	Mutation     *Object
	Subscription *Object
	Types        []Type
	Directives   []*Directive
}

type SerializeFn

type SerializeFn func(value any) any

SerializeFn is a function type for serializing a GraphQLScalar type value

type TracePathCount

type TracePathCount struct {
	Path          []string
	Count         int
	TotalDuration time.Duration
	MaxDuration   time.Duration
}

type Tracer

type Tracer interface {
	Trace(ctx context.Context, path []string, duration time.Duration)
}

type Type

type Type interface {
	Name() string
	Description() string
	String() string
	Error() error
}

Type interface for all of the possible kinds of GraphQL types

type TypeInfo

type TypeInfo struct {
	// contains filtered or unexported fields
}

func NewTypeInfo

func NewTypeInfo(opts *TypeInfoConfig) *TypeInfo

func (*TypeInfo) Argument

func (ti *TypeInfo) Argument() *Argument

func (*TypeInfo) Directive

func (ti *TypeInfo) Directive() *Directive

func (*TypeInfo) Enter

func (ti *TypeInfo) Enter(node ast.Node)

func (*TypeInfo) FieldDef

func (ti *TypeInfo) FieldDef() *FieldDefinition

func (*TypeInfo) InputType

func (ti *TypeInfo) InputType() Input

func (*TypeInfo) Leave

func (ti *TypeInfo) Leave(node ast.Node)

func (*TypeInfo) ParentType

func (ti *TypeInfo) ParentType() Composite

func (*TypeInfo) Type

func (ti *TypeInfo) Type() Output

type TypeInfoConfig

type TypeInfoConfig struct {
	Schema *Schema

	// NOTE: this experimental optional second parameter is only needed in order
	// to support non-spec-compliant codebases. You should never need to use it.
	// It may disappear in the future.
	FieldDefFn fieldDefFn
}

type TypeMap

type TypeMap map[string]Type

type Union

type Union struct {
	PrivateName        string `json:"name"`
	PrivateDescription string `json:"description"`
	ResolveType        ResolveTypeFn
	// contains filtered or unexported fields
}

Union Type Definition

When a field can return one of a heterogeneous set of types, a Union type is used to describe what types are possible as well as providing a function to determine which type is actually used when the field is resolved.

Example:

var PetType = new Union({
  name: 'Pet',
  types: [ DogType, CatType ],
  resolveType(value) {
    if (value instanceof Dog) {
      return DogType;
    }
    if (value instanceof Cat) {
      return CatType;
    }
  }
});

func NewUnion

func NewUnion(config UnionConfig) *Union

func (*Union) Description

func (ut *Union) Description() string

func (*Union) Error

func (ut *Union) Error() error

func (*Union) Name

func (ut *Union) Name() string

func (*Union) String

func (ut *Union) String() string

func (*Union) Types

func (ut *Union) Types() []*Object

type UnionConfig

type UnionConfig struct {
	Name        string    `json:"name"`
	Types       []*Object `json:"types"`
	ResolveType ResolveTypeFn
	Description string `json:"description"`
}

type ValidationContext

type ValidationContext struct {
	// contains filtered or unexported fields
}

func NewValidationContext

func NewValidationContext(schema *Schema, astDoc *ast.Document, typeInfo *TypeInfo) *ValidationContext

func (*ValidationContext) Argument

func (ctx *ValidationContext) Argument() *Argument

func (*ValidationContext) Directive

func (ctx *ValidationContext) Directive() *Directive

func (*ValidationContext) Document

func (ctx *ValidationContext) Document() *ast.Document

func (*ValidationContext) Errors

func (ctx *ValidationContext) Errors() []gqlerrors.FormattedError

func (*ValidationContext) FieldDef

func (ctx *ValidationContext) FieldDef() *FieldDefinition

func (*ValidationContext) Fragment

func (ctx *ValidationContext) Fragment(name string) *ast.FragmentDefinition

func (*ValidationContext) FragmentSpreads

func (ctx *ValidationContext) FragmentSpreads(node HasSelectionSet) []*ast.FragmentSpread

func (*ValidationContext) InputType

func (ctx *ValidationContext) InputType() Input

func (*ValidationContext) ParentType

func (ctx *ValidationContext) ParentType() Composite

func (*ValidationContext) RecursiveVariableUsages

func (ctx *ValidationContext) RecursiveVariableUsages(operation *ast.OperationDefinition) []*VariableUsage

func (*ValidationContext) RecursivelyReferencedFragments

func (ctx *ValidationContext) RecursivelyReferencedFragments(operation *ast.OperationDefinition) []*ast.FragmentDefinition

func (*ValidationContext) ReportError

func (ctx *ValidationContext) ReportError(err error)

func (*ValidationContext) Schema

func (ctx *ValidationContext) Schema() *Schema

func (*ValidationContext) Type

func (ctx *ValidationContext) Type() Output

func (*ValidationContext) VariableUsages

func (ctx *ValidationContext) VariableUsages(node HasSelectionSet) []*VariableUsage

type ValidationResult

type ValidationResult struct {
	IsValid bool
	Errors  []gqlerrors.FormattedError
}

func ValidateDocument

func ValidateDocument(schema *Schema, astDoc *ast.Document, rules []ValidationRuleFn) (vr ValidationResult)

ValidateDocument implements the "Validation" section of the spec.

Validation runs synchronously, returning an array of encountered errors, or an empty array if no errors were encountered and the document is valid.

A list of specific validation rules may be provided. If not provided, the default list of rules defined by the GraphQL specification will be used.

Each validation rules is a function which returns a visitor (see the language/visitor API). Visitor methods are expected to return GraphQLErrors, or Arrays of GraphQLErrors when invalid.

type ValidationRuleFn

type ValidationRuleFn func(context *ValidationContext) *ValidationRuleInstance

type ValidationRuleInstance

type ValidationRuleInstance struct {
	Enter visitor.VisitFunc
	Leave visitor.VisitFunc
}

func ArgumentsOfCorrectTypeRule

func ArgumentsOfCorrectTypeRule(context *ValidationContext) *ValidationRuleInstance

ArgumentsOfCorrectTypeRule Argument values of correct type

A GraphQL document is only valid if all field argument literal values are of the type expected by their position.

func DefaultValuesOfCorrectTypeRule

func DefaultValuesOfCorrectTypeRule(context *ValidationContext) *ValidationRuleInstance

DefaultValuesOfCorrectTypeRule Variable default values of correct type

A GraphQL document is only valid if all variable default values are of the type expected by their definition.

func FieldsOnCorrectTypeRule

func FieldsOnCorrectTypeRule(context *ValidationContext) *ValidationRuleInstance

FieldsOnCorrectTypeRule Fields on correct type

A GraphQL document is only valid if all fields selected are defined by the parent type, or are an allowed meta field such as __typenamme

func FragmentsOnCompositeTypesRule

func FragmentsOnCompositeTypesRule(context *ValidationContext) *ValidationRuleInstance

FragmentsOnCompositeTypesRule Fragments on composite type

Fragments use a type condition to determine if they apply, since fragments can only be spread into a composite type (object, interface, or union), the type condition must also be a composite type.

func KnownArgumentNamesRule

func KnownArgumentNamesRule(context *ValidationContext) *ValidationRuleInstance

KnownArgumentNamesRule Known argument names

A GraphQL field is only valid if all supplied arguments are defined by that field.

func KnownDirectivesRule

func KnownDirectivesRule(context *ValidationContext) *ValidationRuleInstance

KnownDirectivesRule Known directives

A GraphQL document is only valid if all `@directives` are known by the schema and legally positioned.

func KnownFragmentNamesRule

func KnownFragmentNamesRule(context *ValidationContext) *ValidationRuleInstance

KnownFragmentNamesRule Known fragment names

A GraphQL document is only valid if all `...Fragment` fragment spreads refer to fragments defined in the same document.

func KnownTypeNamesRule

func KnownTypeNamesRule(context *ValidationContext) *ValidationRuleInstance

KnownTypeNamesRule Known type names

A GraphQL document is only valid if referenced types (specifically variable definitions and fragment conditions) are defined by the type schema.

func LoneAnonymousOperationRule

func LoneAnonymousOperationRule(context *ValidationContext) *ValidationRuleInstance

LoneAnonymousOperationRule Lone anonymous operation

A GraphQL document is only valid if when it contains an anonymous operation (the query short-hand) that it contains only that one operation definition.

func NoFragmentCyclesRule

func NoFragmentCyclesRule(context *ValidationContext) *ValidationRuleInstance

NoFragmentCyclesRule No fragment cycles

func NoUndefinedVariablesRule

func NoUndefinedVariablesRule(context *ValidationContext) *ValidationRuleInstance

NoUndefinedVariablesRule No undefined variables

A GraphQL operation is only valid if all variables encountered, both directly and via fragment spreads, are defined by that operation.

func NoUnusedFragmentsRule

func NoUnusedFragmentsRule(context *ValidationContext) *ValidationRuleInstance

NoUnusedFragmentsRule No unused fragments

A GraphQL document is only valid if all fragment definitions are spread within operations, or spread within other fragments spread within operations.

func NoUnusedVariablesRule

func NoUnusedVariablesRule(context *ValidationContext) *ValidationRuleInstance

NoUnusedVariablesRule No unused variables

A GraphQL operation is only valid if all variables defined by an operation are used, either directly or within a spread fragment.

func OverlappingFieldsCanBeMergedRule

func OverlappingFieldsCanBeMergedRule(context *ValidationContext) *ValidationRuleInstance

OverlappingFieldsCanBeMergedRule Overlapping fields can be merged

A selection set is only valid if all fields (including spreading any fragments) either correspond to distinct response names or can be merged without ambiguity.

func PossibleFragmentSpreadsRule

func PossibleFragmentSpreadsRule(context *ValidationContext) *ValidationRuleInstance

PossibleFragmentSpreadsRule Possible fragment spread

A fragment spread is only valid if the type condition could ever possibly be true: if there is a non-empty intersection of the possible parent types, and possible types which pass the type condition.

func ProvidedNonNullArgumentsRule

func ProvidedNonNullArgumentsRule(context *ValidationContext) *ValidationRuleInstance

ProvidedNonNullArgumentsRule Provided required arguments

A field or directive is only valid if all required (non-null) field arguments have been provided.

func ScalarLeafsRule

func ScalarLeafsRule(context *ValidationContext) *ValidationRuleInstance

ScalarLeafsRule Scalar leafs

A GraphQL document is valid only if all leaf fields (fields without sub selections) are of scalar or enum types.

func UniqueArgumentNamesRule

func UniqueArgumentNamesRule(context *ValidationContext) *ValidationRuleInstance

UniqueArgumentNamesRule Unique argument names

A GraphQL field or directive is only valid if all supplied arguments are uniquely named.

func UniqueFragmentNamesRule

func UniqueFragmentNamesRule(context *ValidationContext) *ValidationRuleInstance

UniqueFragmentNamesRule Unique fragment names

A GraphQL document is only valid if all defined fragments have unique names.

func UniqueInputFieldNamesRule

func UniqueInputFieldNamesRule(context *ValidationContext) *ValidationRuleInstance

UniqueInputFieldNamesRule Unique input field names

A GraphQL input object value is only valid if all supplied fields are uniquely named.

func UniqueOperationNamesRule

func UniqueOperationNamesRule(context *ValidationContext) *ValidationRuleInstance

UniqueOperationNamesRule Unique operation names

A GraphQL document is only valid if all defined operations have unique names.

func UniqueVariableNamesRule

func UniqueVariableNamesRule(context *ValidationContext) *ValidationRuleInstance

UniqueVariableNamesRule Unique variable names

A GraphQL operation is only valid if all its variables are uniquely named.

func VariablesAreInputTypesRule

func VariablesAreInputTypesRule(context *ValidationContext) *ValidationRuleInstance

VariablesAreInputTypesRule Variables are input types

A GraphQL operation is only valid if all the variables it defines are of input types (scalar, enum, or input object).

func VariablesInAllowedPositionRule

func VariablesInAllowedPositionRule(context *ValidationContext) *ValidationRuleInstance

VariablesInAllowedPositionRule Variables passed to field arguments conform to type

type VariableUsage

type VariableUsage struct {
	Node *ast.Variable
	Type Input
}

Directories

Path Synopsis
cmd
graphql2go command
examples
context command
hello-world command
http command
httpdynamic command
star-wars command
todo command
Package gqldecode provides a decoder that unmarshals GraphQL input arguments into a struct.
Package gqldecode provides a decoder that unmarshals GraphQL input arguments into a struct.
language
ast

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL