graphql

package module
v0.0.0-...-8ceed3f Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2016 License: MIT Imports: 17 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) (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”}}
}

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 (
	TypeKindScalar      = "SCALAR"
	TypeKindObject      = "OBJECT"
	TypeKindInterface   = "INTERFACE"
	TypeKindUnion       = "UNION"
	TypeKindEnum        = "ENUM"
	TypeKindInputObject = "INPUT_OBJECT"
	TypeKindList        = "LIST"
	TypeKindNonNull     = "NON_NULL"
)

Variables

View Source
var NAME_REGEXP, _ = regexp.Compile("^[_a-zA-Z][_a-zA-Z0-9]*$")

*

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

Functions

func FieldASTsToNodeASTs

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

func IsCompositeType

func IsCompositeType(ttype interface{}) bool

func IsInputType

func IsInputType(ttype Type) bool

func IsLeafType

func IsLeafType(ttype Type) bool

func IsOutputType

func IsOutputType(ttype Type) bool

func NewLocatedError

func NewLocatedError(err interface{}, nodes []ast.Node) *gqlerrors.Error

Types

type Abstract

type Abstract interface {
	ObjectType(value interface{}, info ResolveInfo) *Object
	PossibleTypes() []*Object
	IsPossibleType(ttype *Object) bool
}

These types may describe the parent context of a selection set.

type Argument

type Argument struct {
	PrivateName        string      `json:"name"`
	Type               Input       `json:"type"`
	DefaultValue       interface{} `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 interface{} `json:"defaultValue"`
	Description  string      `json:"description"`
}

type BuildExecutionCtxParams

type BuildExecutionCtxParams struct {
	Schema        Schema
	Root          interface{}
	AST           *ast.Document
	OperationName string
	Args          map[string]interface{}
	Errors        []gqlerrors.FormattedError
	Result        *Result
	Context       context.Context
}

type CollectFieldsParams

type CollectFieldsParams struct {
	ExeContext           *ExecutionContext
	OperationType        *Object
	SelectionSet         *ast.SelectionSet
	Fields               map[string][]*ast.Field
	VisitedFragmentNames map[string]bool
}

type Composite

type Composite interface {
	Name() string
}

These types may describe the parent context of a selection set.

type Directive

type Directive struct {
	Name        string      `json:"name"`
	Description string      `json:"description"`
	Args        []*Argument `json:"args"`
	OnOperation bool        `json:"onOperation"`
	OnFragment  bool        `json:"onFragment"`
	OnField     bool        `json:"onField"`
}
var IncludeDirective *Directive = NewDirective(&Directive{
	Name: "include",
	Description: "Directs the executor to include this field or fragment only when " +
		"the `if` argument is true.",
	Args: []*Argument{
		&Argument{
			PrivateName:        "if",
			Type:               NewNonNull(Boolean),
			PrivateDescription: "Included when true.",
		},
	},
	OnOperation: false,
	OnFragment:  true,
	OnField:     true,
})

*

  • Used to conditionally include fields or fragments
var SkipDirective *Directive = NewDirective(&Directive{
	Name: "skip",
	Description: "Directs the executor to skip this field or fragment when the `if` " +
		"argument is true.",
	Args: []*Argument{
		&Argument{
			PrivateName:        "if",
			Type:               NewNonNull(Boolean),
			PrivateDescription: "Skipped when true.",
		},
	},
	OnOperation: false,
	OnFragment:  true,
	OnField:     true,
})

*

  • Used to conditionally skip (exclude) fields or fragments

func NewDirective

func NewDirective(config *Directive) *Directive

*

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

type Enum

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

*

  • Enum Type Definition *
  • Some leaf values of requests and input values are Enums. GraphQL serializes
  • Enum values as strings, however internally Enums can be represented by any
  • kind of type, often integers. *
  • Example: *
  • var RGBType = new Enum({
  • name: 'RGB',
  • values: {
  • RED: { value: 0 },
  • GREEN: { value: 1 },
  • BLUE: { value: 2 }
  • }
  • }); *
  • Note: If a value is not provided in a definition, the name of the enum value
  • will be used as it's internal value.

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) interface{}

func (*Enum) ParseValue

func (gt *Enum) ParseValue(value interface{}) interface{}

func (*Enum) Serialize

func (gt *Enum) Serialize(value interface{}) interface{}

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             interface{} `json:"value"`
	DeprecationReason string      `json:"deprecationReason"`
	Description       string      `json:"description"`
}

type EnumValueConfigMap

type EnumValueConfigMap map[string]*EnumValueConfig

type EnumValueDefinition

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

type ExecuteFieldsParams

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

type ExecuteOperationParams

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

type ExecuteParams

type ExecuteParams struct {
	Schema        Schema
	Root          interface{}
	AST           *ast.Document
	OperationName string
	Args          map[string]interface{}

	// Context may be provided to pass application-specific per-request
	// information to resolve functions.
	Context context.Context
}

type ExecutionContext

type ExecutionContext struct {
	Schema         Schema
	Fragments      map[string]ast.Definition
	Root           interface{}
	Operation      ast.Definition
	VariableValues map[string]interface{}
	Errors         []gqlerrors.FormattedError
	Context        context.Context
}

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"`
	Description       string `json:"description"`
}

type FieldArgument

type FieldArgument struct {
	Name         string      `json:"name"`
	Type         Type        `json:"type"`
	DefaultValue interface{} `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"`
}
var SchemaMetaFieldDef *FieldDefinition
var TypeMetaFieldDef *FieldDefinition
var TypeNameMetaFieldDef *FieldDefinition

func TypeInfoFieldDef

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

*

  • 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(p ResolveParams) (interface{}, error)

TODO: relook at FieldResolveFn params

type Fields

type Fields map[string]*Field

type FieldsThunk

type FieldsThunk func() Fields

type Input

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

These types 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
}

*

  • Input Object 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

TODO: rename InputObjectConfig to GraphQLInputObjecTypeConfig for consistency?

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      interface{} `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       interface{} `json:"defaultValue"`
	PrivateDescription string      `json:"description"`
}

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 interface{} `json:"defaultValue"`
	Description  string      `json:"description"`
}

type InputObjectFieldMap

type InputObjectFieldMap 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() (fields FieldDefinitionMap)

func (*Interface) IsPossibleType

func (it *Interface) IsPossibleType(ttype *Object) bool

func (*Interface) Name

func (it *Interface) Name() string

func (*Interface) ObjectType

func (it *Interface) ObjectType(value interface{}, info ResolveInfo) *Object

func (*Interface) PossibleTypes

func (it *Interface) PossibleTypes() []*Object

func (*Interface) String

func (it *Interface) String() string

type InterfaceConfig

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

type InterfacesThunk

type InterfacesThunk func() []*Interface

type IsTypeOfFn

type IsTypeOfFn func(value interface{}, info ResolveInfo) bool

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
}

These named types do not include modifiers like List or NonNull.

func GetNamed

func GetNamed(ttype Type) Named

type NonNull

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

*

  • Non-Null 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 {
}

func GetNullable

func GetNullable(ttype Type) Nullable

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:"description"`
	Interfaces  interface{} `json:"interfaces"`
	Fields      interface{} `json:"fields"`
	IsTypeOf    IsTypeOfFn  `json:"isTypeOf"`
	Description string      `json:"description"`
}

type Output

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

These types may be used as output types as the result of fields.

type Params

type Params struct {
	Schema         Schema
	RequestString  string
	RootObject     map[string]interface{}
	VariableValues map[string]interface{}
	OperationName  string

	// Context may be provided to pass application-specific per-request
	// information to resolve functions.
	Context context.Context
}

type ParseLiteralFn

type ParseLiteralFn func(valueAST ast.Value) interface{}

type ParseValueFn

type ParseValueFn func(value interface{}) interface{}

type ResolveInfo

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

type ResolveParams

type ResolveParams struct {
	Source interface{}
	Args   map[string]interface{}
	Info   ResolveInfo
	Schema Schema
	//This can be used to provide per-request state
	//from the application.
	Context context.Context
}

TODO: clean up GQLFRParams fields

type ResolveTypeFn

type ResolveTypeFn func(value interface{}, info ResolveInfo) *Object

type Result

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

func Do

func Do(p Params) *Result

func Execute

func Execute(p ExecuteParams) (result *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;
  • }
  • }); *
var Boolean *Scalar = NewScalar(ScalarConfig{
	Name:       "Boolean",
	Serialize:  coerceBool,
	ParseValue: coerceBool,
	ParseLiteral: func(valueAST ast.Value) interface{} {
		switch valueAST := valueAST.(type) {
		case *ast.BooleanValue:
			return valueAST.Value
		}
		return nil
	},
})

Boolean is the GraphQL boolean type definition

var Float *Scalar = NewScalar(ScalarConfig{
	Name:       "Float",
	Serialize:  coerceFloat32,
	ParseValue: coerceFloat32,
	ParseLiteral: func(valueAST ast.Value) interface{} {
		switch valueAST := valueAST.(type) {
		case *ast.FloatValue:
			if floatValue, err := strconv.ParseFloat(valueAST.Value, 32); err == nil {
				return floatValue
			}
		case *ast.IntValue:
			if floatValue, err := strconv.ParseFloat(valueAST.Value, 32); err == nil {
				return floatValue
			}
		}
		return nil
	},
})

Float is the GraphQL float type definition.

var ID *Scalar = NewScalar(ScalarConfig{
	Name:       "ID",
	Serialize:  coerceString,
	ParseValue: coerceString,
	ParseLiteral: func(valueAST ast.Value) interface{} {
		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

var Int *Scalar = NewScalar(ScalarConfig{
	Name:       "Int",
	Serialize:  coerceInt,
	ParseValue: coerceInt,
	ParseLiteral: func(valueAST ast.Value) interface{} {
		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.

var String *Scalar = NewScalar(ScalarConfig{
	Name:       "String",
	Serialize:  coerceString,
	ParseValue: coerceString,
	ParseLiteral: func(valueAST ast.Value) interface{} {
		switch valueAST := valueAST.(type) {
		case *ast.StringValue:
			return valueAST.Value
		}
		return nil
	},
})

String is the GraphQL string type definition

func NewScalar

func NewScalar(config ScalarConfig) *Scalar

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) interface{}

func (*Scalar) ParseValue

func (st *Scalar) ParseValue(value interface{}) interface{}

func (*Scalar) Serialize

func (st *Scalar) Serialize(value interface{}) interface{}

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
}

type Schema

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

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) MutationType

func (gq *Schema) MutationType() *Object

func (*Schema) QueryType

func (gq *Schema) QueryType() *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
}

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

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

type SerializeFn

type SerializeFn func(value interface{}) interface{}

type Type

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

These are all of the possible kinds of

type TypeInfo

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

TODO: can move TypeInfo to a utils package if there ever is one *

  • TypeInfo is a utility class which, given a GraphQL schema, can keep track
  • of the current field and type definitions at any point in a GraphQL document
  • AST during a recursive descent by calling `enter(node)` and `leave(node)`.

func NewTypeInfo

func NewTypeInfo(schema *Schema) *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 TypeMap

type TypeMap map[string]Type

chose to name as TypeMap instead of TypeMap

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) IsPossibleType

func (ut *Union) IsPossibleType(ttype *Object) bool

func (*Union) Name

func (ut *Union) Name() string

func (*Union) ObjectType

func (ut *Union) ObjectType(value interface{}, info ResolveInfo) *Object

func (*Union) PossibleTypes

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

func (*Union) String

func (ut *Union) String() string

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) FieldDef

func (ctx *ValidationContext) FieldDef() *FieldDefinition

func (*ValidationContext) Fragment

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

func (*ValidationContext) InputType

func (ctx *ValidationContext) InputType() Input

func (*ValidationContext) ParentType

func (ctx *ValidationContext) ParentType() Composite

func (*ValidationContext) Schema

func (ctx *ValidationContext) Schema() *Schema

func (*ValidationContext) Type

func (ctx *ValidationContext) Type() Output

type ValidationResult

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

func ValidateDocument

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

type ValidationRuleFn

type ValidationRuleFn func(context *ValidationContext) *ValidationRuleInstance

type ValidationRuleInstance

type ValidationRuleInstance struct {
	VisitorOpts          *visitor.VisitorOptions
	VisitSpreadFragments bool
}

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

*

  • 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

func NoUndefinedVariablesRule

func NoUndefinedVariablesRule(context *ValidationContext) *ValidationRuleInstance

*

  • NoUndefinedVariables
  • 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 UniqueOperationNamesRule

func UniqueOperationNamesRule(context *ValidationContext) *ValidationRuleInstance

*

  • UniqueOperationNamesRule
  • Unique operation names *
  • A GraphQL document is only valid if all defined operations have unique names.

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

Directories

Path Synopsis
examples
language
ast

Jump to

Keyboard shortcuts

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