graphql: github.com/graphql-go/graphql Index | Files | Directories

package graphql

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

Index

Package Files

definition.go directives.go executor.go graphql.go introspection.go located.go rules.go rules_overlapping_fields_can_be_merged.go scalars.go schema.go type_info.go types.go util.go validator.go values.go

Constants

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

DefaultDeprecationReason Constant string used for default reason for a deprecation.

const TAG = "json"

Variables

var Boolean = NewScalar(ScalarConfig{
    Name:        "Boolean",
    Description: "The `Boolean` scalar type represents `true` or `false`.",
    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 DateTime = NewScalar(ScalarConfig{
    Name: "DateTime",
    Description: "The `DateTime` scalar type represents a DateTime." +
        " The DateTime is serialized as an RFC 3339 quoted string",
    Serialize:  serializeDateTime,
    ParseValue: unserializeDateTime,
    ParseLiteral: func(valueAST ast.Value) interface{} {
        switch valueAST := valueAST.(type) {
        case *ast.StringValue:
            return valueAST.Value
        }
        return nil
    },
})
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.

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:  coerceFloat,
    ParseValue: coerceFloat,
    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 = 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) 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 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.

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) 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 NameRegExp = regexp.Compile("^[_a-zA-Z][_a-zA-Z0-9]*$")
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.

var SpecifiedDirectives = []*Directive{
    IncludeDirective,
    SkipDirective,
    DeprecatedDirective,
}

SpecifiedRules The full list of specified directives.

var SpecifiedRules = []ValidationRuleFn{
    ArgumentsOfCorrectTypeRule,
    DefaultValuesOfCorrectTypeRule,
    FieldsOnCorrectTypeRule,
    FragmentsOnCompositeTypesRule,
    KnownArgumentNamesRule,
    KnownDirectivesRule,
    KnownFragmentNamesRule,
    KnownTypeNamesRule,
    LoneAnonymousOperationRule,
    NoFragmentCyclesRule,
    NoUndefinedVariablesRule,
    NoUnusedFragmentsRule,
    NoUnusedVariablesRule,
    OverlappingFieldsCanBeMergedRule,
    PossibleFragmentSpreadsRule,
    ProvidedNonNullArgumentsRule,
    ScalarLeafsRule,
    UniqueArgumentNamesRule,
    UniqueFragmentNamesRule,
    UniqueInputFieldNamesRule,
    UniqueOperationNamesRule,
    UniqueVariableNamesRule,
    VariablesAreInputTypesRule,
    VariablesInAllowedPositionRule,
}

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

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) interface{} {
        switch valueAST := valueAST.(type) {
        case *ast.StringValue:
            return valueAST.Value
        }
        return nil
    },
})

String is the GraphQL string type definition

func CycleErrorMessage Uses

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

func DefaultResolveFn Uses

func DefaultResolveFn(p ResolveParams) (interface{}, error)

defaultResolveFn If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object of the same name as the field and returns it as the result, or if it's a function, returns the result of calling that function.

func FieldASTsToNodeASTs Uses

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

func IsAbstractType Uses

func IsAbstractType(ttype interface{}) bool

func IsCompositeType Uses

func IsCompositeType(ttype interface{}) bool

IsCompositeType determines if given type is a GraphQLComposite type

func IsInputType Uses

func IsInputType(ttype Type) bool

IsInputType determines if given type is a GraphQLInputType

func IsLeafType Uses

func IsLeafType(ttype Type) bool

IsLeafType determines if given type is a leaf value

func IsOutputType Uses

func IsOutputType(ttype Type) bool

IsOutputType determines if given type is a GraphQLOutputType

func MisplaceDirectiveMessage Uses

func MisplaceDirectiveMessage(directiveName string, location string) string

func NewLocatedError Uses

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

func UndefinedFieldMessage Uses

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

func UndefinedVarMessage Uses

func UndefinedVarMessage(varName string, opName string) string

func UnusedVariableMessage Uses

func UnusedVariableMessage(varName string, opName string) string

func VisitUsingRules Uses

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

type Abstract Uses

type Abstract interface {
    Name() string
}

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

type Argument Uses

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

func (*Argument) Description Uses

func (st *Argument) Description() string

func (*Argument) Error Uses

func (st *Argument) Error() error

func (*Argument) Name Uses

func (st *Argument) Name() string

func (*Argument) String Uses

func (st *Argument) String() string

type ArgumentConfig Uses

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

type BuildExecutionCtxParams Uses

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 Uses

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

type Composite Uses

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 Directive Uses

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 Uses

func NewDirective(config DirectiveConfig) *Directive

type DirectiveConfig Uses

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 Uses

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

DirectiveLocationEnumType is type definition for __DirectiveLocation

var TypeKindEnumType *Enum

TypeKindEnumType is type definition for __TypeKind

func NewEnum Uses

func NewEnum(config EnumConfig) *Enum

func (*Enum) Description Uses

func (gt *Enum) Description() string

func (*Enum) Error Uses

func (gt *Enum) Error() error

func (*Enum) Name Uses

func (gt *Enum) Name() string

func (*Enum) ParseLiteral Uses

func (gt *Enum) ParseLiteral(valueAST ast.Value) interface{}

func (*Enum) ParseValue Uses

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

func (*Enum) Serialize Uses

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

func (*Enum) String Uses

func (gt *Enum) String() string

func (*Enum) Values Uses

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

type EnumConfig Uses

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

type EnumValueConfig Uses

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

type EnumValueConfigMap Uses

type EnumValueConfigMap map[string]*EnumValueConfig

type EnumValueDefinition Uses

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

type ExecuteFieldsParams Uses

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

type ExecuteOperationParams Uses

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

type ExecuteParams Uses

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 Uses

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 Uses

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 Uses

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

type FieldConfigArgument Uses

type FieldConfigArgument map[string]*ArgumentConfig

func BindArg Uses

func BindArg(obj interface{}, tags ...string) FieldConfigArgument

lazy way of binding args

type FieldDefinition Uses

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

SchemaMetaFieldDef Meta field definition for Schema

var TypeMetaFieldDef *FieldDefinition

TypeMetaFieldDef Meta field definition for types

var TypeNameMetaFieldDef *FieldDefinition

TypeNameMetaFieldDef Meta field definition for type names

func DefaultTypeInfoFieldDef Uses

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 Uses

type FieldDefinitionMap map[string]*FieldDefinition

type FieldResolveFn Uses

type FieldResolveFn func(p ResolveParams) (interface{}, error)

type Fields Uses

type Fields map[string]*Field

func BindFields Uses

func BindFields(obj interface{}) Fields

can't take recursive slice type e.g type Person struct{

Friends []Person

} it will throw panic stack-overflow

type FieldsThunk Uses

type FieldsThunk func() Fields

type HasSelectionSet Uses

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

type Input Uses

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 Uses

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 Uses

func NewInputObject(config InputObjectConfig) *InputObject

func (*InputObject) Description Uses

func (gt *InputObject) Description() string

func (*InputObject) Error Uses

func (gt *InputObject) Error() error

func (*InputObject) Fields Uses

func (gt *InputObject) Fields() InputObjectFieldMap

func (*InputObject) Name Uses

func (gt *InputObject) Name() string

func (*InputObject) String Uses

func (gt *InputObject) String() string

type InputObjectConfig Uses

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

type InputObjectConfigFieldMap Uses

type InputObjectConfigFieldMap map[string]*InputObjectFieldConfig

type InputObjectConfigFieldMapThunk Uses

type InputObjectConfigFieldMapThunk func() InputObjectConfigFieldMap

type InputObjectField Uses

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

func (*InputObjectField) Description Uses

func (st *InputObjectField) Description() string

func (*InputObjectField) Error Uses

func (st *InputObjectField) Error() error

func (*InputObjectField) Name Uses

func (st *InputObjectField) Name() string

func (*InputObjectField) String Uses

func (st *InputObjectField) String() string

type InputObjectFieldConfig Uses

type InputObjectFieldConfig struct {
    Type         Input       `json:"type"`
    DefaultValue interface{} `json:"defaultValue"`
    Description  string      `json:"description"`
}

type InputObjectFieldMap Uses

type InputObjectFieldMap map[string]*InputObjectField

type Interface Uses

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 Uses

func NewInterface(config InterfaceConfig) *Interface

func (*Interface) AddFieldConfig Uses

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

func (*Interface) Description Uses

func (it *Interface) Description() string

func (*Interface) Error Uses

func (it *Interface) Error() error

func (*Interface) Fields Uses

func (it *Interface) Fields() (fields FieldDefinitionMap)

func (*Interface) Name Uses

func (it *Interface) Name() string

func (*Interface) String Uses

func (it *Interface) String() string

type InterfaceConfig Uses

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

type InterfacesThunk Uses

type InterfacesThunk func() []*Interface

type IsTypeOfFn Uses

type IsTypeOfFn func(p IsTypeOfParams) bool

type IsTypeOfParams Uses

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

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

    // Context argument is a context value that is provided to every resolve function within an execution.
    // It is commonly
    // used to represent an authenticated user, or request-specific caches.
    Context context.Context
}

IsTypeOfParams Params for IsTypeOfFn()

type Leaf Uses

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

Leaf interface for types that may be leaf values

type List Uses

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 Uses

func NewList(ofType Type) *List

func (*List) Description Uses

func (gl *List) Description() string

func (*List) Error Uses

func (gl *List) Error() error

func (*List) Name Uses

func (gl *List) Name() string

func (*List) String Uses

func (gl *List) String() string

type Named Uses

type Named interface {
    String() string
}

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

func GetNamed Uses

func GetNamed(ttype Type) Named

GetNamed returns the Named type of the given GraphQL type

type NonNull Uses

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 Uses

func NewNonNull(ofType Type) *NonNull

func (*NonNull) Description Uses

func (gl *NonNull) Description() string

func (*NonNull) Error Uses

func (gl *NonNull) Error() error

func (*NonNull) Name Uses

func (gl *NonNull) Name() string

func (*NonNull) String Uses

func (gl *NonNull) String() string

type Nullable Uses

type Nullable interface {
}

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

func GetNullable Uses

func GetNullable(ttype Type) Nullable

GetNullable returns the Nullable type of the given GraphQL type

type Object Uses

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 },
  })
});

/

var DirectiveType *Object

DirectiveType is type definition for __Directive

var EnumValueType *Object

EnumValueType is type definition for __EnumValue

var FieldType *Object

FieldType is type definition for __Field

var InputValueType *Object

InputValueType is type definition for __InputValue

var SchemaType *Object

SchemaType is type definition for __Schema

var TypeType *Object

TypeType is type definition for __Type

func NewObject Uses

func NewObject(config ObjectConfig) *Object

func (*Object) AddFieldConfig Uses

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

func (*Object) Description Uses

func (gt *Object) Description() string

func (*Object) Error Uses

func (gt *Object) Error() error

func (*Object) Fields Uses

func (gt *Object) Fields() FieldDefinitionMap

func (*Object) Interfaces Uses

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

func (*Object) Name Uses

func (gt *Object) Name() string

func (*Object) String Uses

func (gt *Object) String() string

type ObjectConfig Uses

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

type Output Uses

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 Uses

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

    // A GraphQL language formatted string representing the requested operation.
    RequestString string

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

    // A mapping of variable name to runtime value to use for all variables
    // defined in the requestString.
    VariableValues map[string]interface{}

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

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

type ParseLiteralFn Uses

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

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

type ParseValueFn Uses

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

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

type ResolveInfo Uses

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 Uses

type ResolveParams struct {
    // Source is the source value
    Source interface{}

    // Args is a map of arguments for current GraphQL request
    Args map[string]interface{}

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

    // Context argument is a context value that is provided to every resolve function within an execution.
    // It is commonly
    // used to represent an authenticated user, or request-specific caches.
    Context context.Context
}

ResolveParams Params for FieldResolveFn()

type ResolveTypeFn Uses

type ResolveTypeFn func(p ResolveTypeParams) *Object

type ResolveTypeParams Uses

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

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

    // Context argument is a context value that is provided to every resolve function within an execution.
    // It is commonly
    // used to represent an authenticated user, or request-specific caches.
    Context context.Context
}

ResolveTypeParams Params for ResolveTypeFn()

type Result Uses

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

func Do Uses

func Do(p Params) *Result

func Execute Uses

func Execute(p ExecuteParams) (result *Result)

func (*Result) HasErrors Uses

func (r *Result) HasErrors() bool

type Scalar Uses

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 Uses

func NewScalar(config ScalarConfig) *Scalar

NewScalar creates a new GraphQLScalar

func (*Scalar) Description Uses

func (st *Scalar) Description() string

func (*Scalar) Error Uses

func (st *Scalar) Error() error

func (*Scalar) Name Uses

func (st *Scalar) Name() string

func (*Scalar) ParseLiteral Uses

func (st *Scalar) ParseLiteral(valueAST ast.Value) interface{}

func (*Scalar) ParseValue Uses

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

func (*Scalar) Serialize Uses

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

func (*Scalar) String Uses

func (st *Scalar) String() string

type ScalarConfig Uses

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 Uses

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 Uses

func NewSchema(config SchemaConfig) (Schema, error)

func (*Schema) AddImplementation Uses

func (gq *Schema) AddImplementation() error

Added Check implementation of interfaces at runtime.. Add Implementations at Runtime..

func (*Schema) AppendType Uses

func (gq *Schema) AppendType(objectType Type) error

Edited. To check add Types at RunTime.. Append Runtime schema to typeMap

func (*Schema) Directive Uses

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

func (*Schema) Directives Uses

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

func (*Schema) IsPossibleType Uses

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

func (*Schema) MutationType Uses

func (gq *Schema) MutationType() *Object

func (*Schema) PossibleTypes Uses

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

func (*Schema) QueryType Uses

func (gq *Schema) QueryType() *Object

func (*Schema) SubscriptionType Uses

func (gq *Schema) SubscriptionType() *Object

func (*Schema) Type Uses

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

func (*Schema) TypeMap Uses

func (gq *Schema) TypeMap() TypeMap

type SchemaConfig Uses

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

type SerializeFn Uses

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

SerializeFn is a function type for serializing a GraphQLScalar type value

type Type Uses

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

Type interface for all of the possible kinds of GraphQL types

type TypeInfo Uses

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

func NewTypeInfo Uses

func NewTypeInfo(opts *TypeInfoConfig) *TypeInfo

func (*TypeInfo) Argument Uses

func (ti *TypeInfo) Argument() *Argument

func (*TypeInfo) Directive Uses

func (ti *TypeInfo) Directive() *Directive

func (*TypeInfo) Enter Uses

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

func (*TypeInfo) FieldDef Uses

func (ti *TypeInfo) FieldDef() *FieldDefinition

func (*TypeInfo) InputType Uses

func (ti *TypeInfo) InputType() Input

func (*TypeInfo) Leave Uses

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

func (*TypeInfo) ParentType Uses

func (ti *TypeInfo) ParentType() Composite

func (*TypeInfo) Type Uses

func (ti *TypeInfo) Type() Output

type TypeInfoConfig Uses

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 Uses

type TypeMap map[string]Type

type Union Uses

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 Uses

func NewUnion(config UnionConfig) *Union

func (*Union) Description Uses

func (ut *Union) Description() string

func (*Union) Error Uses

func (ut *Union) Error() error

func (*Union) Name Uses

func (ut *Union) Name() string

func (*Union) String Uses

func (ut *Union) String() string

func (*Union) Types Uses

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

type UnionConfig Uses

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

type ValidationContext Uses

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

func NewValidationContext Uses

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

func (*ValidationContext) Argument Uses

func (ctx *ValidationContext) Argument() *Argument

func (*ValidationContext) Directive Uses

func (ctx *ValidationContext) Directive() *Directive

func (*ValidationContext) Document Uses

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

func (*ValidationContext) Errors Uses

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

func (*ValidationContext) FieldDef Uses

func (ctx *ValidationContext) FieldDef() *FieldDefinition

func (*ValidationContext) Fragment Uses

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

func (*ValidationContext) FragmentSpreads Uses

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

func (*ValidationContext) InputType Uses

func (ctx *ValidationContext) InputType() Input

func (*ValidationContext) ParentType Uses

func (ctx *ValidationContext) ParentType() Composite

func (*ValidationContext) RecursiveVariableUsages Uses

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

func (*ValidationContext) RecursivelyReferencedFragments Uses

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

func (*ValidationContext) ReportError Uses

func (ctx *ValidationContext) ReportError(err error)

func (*ValidationContext) Schema Uses

func (ctx *ValidationContext) Schema() *Schema

func (*ValidationContext) Type Uses

func (ctx *ValidationContext) Type() Output

func (*ValidationContext) VariableUsages Uses

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

type ValidationResult Uses

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

func ValidateDocument Uses

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

type ValidationRuleFn Uses

type ValidationRuleFn func(context *ValidationContext) *ValidationRuleInstance

type ValidationRuleInstance Uses

type ValidationRuleInstance struct {
    VisitorOpts *visitor.VisitorOptions
}

func ArgumentsOfCorrectTypeRule Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

func NoFragmentCyclesRule(context *ValidationContext) *ValidationRuleInstance

NoFragmentCyclesRule No fragment cycles

func NoUndefinedVariablesRule Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

func UniqueFragmentNamesRule(context *ValidationContext) *ValidationRuleInstance

UniqueFragmentNamesRule Unique fragment names

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

func UniqueInputFieldNamesRule Uses

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 Uses

func UniqueOperationNamesRule(context *ValidationContext) *ValidationRuleInstance

UniqueOperationNamesRule Unique operation names

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

func UniqueVariableNamesRule Uses

func UniqueVariableNamesRule(context *ValidationContext) *ValidationRuleInstance

UniqueVariableNamesRule Unique variable names

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

func VariablesAreInputTypesRule Uses

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 Uses

func VariablesInAllowedPositionRule(context *ValidationContext) *ValidationRuleInstance

VariablesInAllowedPositionRule Variables passed to field arguments conform to type

type VariableUsage Uses

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

Directories

PathSynopsis
examples/context
examples/hello-world
examples/http
examples/httpdynamic
examples/star-wars
examples/todo
gqlerrors
language/ast
language/kinds
language/lexer
language/location
language/parser
language/printer
language/source
language/typeInfo
language/visitor
testutil

Package graphql imports 18 packages (graph) and is imported by 81 packages. Updated 2017-11-16. Refresh now. Tools for package owners.