Documentation
¶
Index ¶
- Constants
- Variables
- func CycleErrorMessage(fragName string, spreadNames []string) string
- func DefaultResolveFn(p ResolveParams) (interface{}, error)
- func ExecuteSubscription(p ExecuteParams) chan *Result
- func FieldASTsToNodeASTs(fieldASTs []*ast.Field) []ast.Node
- func IsAbstractType(ttype interface{}) bool
- func IsCompositeType(ttype interface{}) bool
- func IsInputType(ttype Type) bool
- func IsLeafType(ttype Type) bool
- func IsOutputType(ttype Type) bool
- func MetadataValue[T any](m Metadata, key string) (T, bool)
- func MisplaceDirectiveMessage(directiveName string, location string) string
- func NewLocatedError(err interface{}, nodes []ast.Node) *gqlerrors.Error
- func NewLocatedErrorWithPath(err interface{}, nodes []ast.Node, path []interface{}) *gqlerrors.Error
- func Subscribe(p Params) chan *Result
- func UndefinedFieldMessage(fieldName string, ttypeName string, suggestedTypeNames []string, ...) string
- func UndefinedVarMessage(varName string, opName string) string
- func UnusedVariableMessage(varName string, opName string) string
- func VisitUsingRules(schema *Schema, typeInfo *TypeInfo, astDoc *ast.Document, ...) []gqlerrors.FormattedError
- type Abstract
- type Argument
- type ArgumentConfig
- type ArgumentState
- type CoercionConfig
- type CoercionDifference
- type CoercionDifferenceKind
- type CoercionMode
- type Composite
- type Directive
- type DirectiveConfig
- type Enum
- func (gt *Enum) Description() string
- func (gt *Enum) Error() error
- func (gt *Enum) Metadata() Metadata
- func (gt *Enum) Name() string
- func (gt *Enum) ParseLiteral(valueAST ast.Value) interface{}
- func (gt *Enum) ParseValue(value interface{}) interface{}
- func (gt *Enum) Serialize(value interface{}) interface{}
- func (gt *Enum) String() string
- func (gt *Enum) Values() []*EnumValueDefinition
- type EnumConfig
- type EnumValueConfig
- type EnumValueConfigMap
- type EnumValueDefinition
- type ExecuteParams
- type ExecutionFinishFunc
- type Extension
- type Field
- type FieldArgument
- type FieldConfigArgument
- type FieldDefinition
- type FieldDefinitionMap
- type FieldResolveFn
- type FieldResolver
- type Fields
- type FieldsThunk
- type HasSelectionSet
- type Input
- type InputObject
- func (gt *InputObject) AddFieldConfig(fieldName string, fieldConfig *InputObjectFieldConfig)
- func (gt *InputObject) Description() string
- func (gt *InputObject) Error() error
- func (gt *InputObject) Fields() InputObjectFieldMap
- func (gt *InputObject) Metadata() Metadata
- func (gt *InputObject) Name() string
- func (gt *InputObject) String() string
- type InputObjectConfig
- type InputObjectConfigFieldMap
- type InputObjectConfigFieldMapThunk
- type InputObjectField
- type InputObjectFieldConfig
- type InputObjectFieldMap
- type Interface
- func (it *Interface) AddFieldConfig(fieldName string, fieldConfig *Field)
- func (it *Interface) Description() string
- func (it *Interface) Error() error
- func (it *Interface) Fields() (fields FieldDefinitionMap)
- func (it *Interface) Metadata() Metadata
- func (it *Interface) Name() string
- func (it *Interface) String() string
- type InterfaceConfig
- type InterfacesThunk
- type IsTypeOfFn
- type IsTypeOfParams
- type Leaf
- type List
- type Metadata
- type Named
- type NonNull
- type Nullable
- type Object
- func (gt *Object) AddFieldConfig(fieldName string, fieldConfig *Field)
- func (gt *Object) Description() string
- func (gt *Object) Error() error
- func (gt *Object) Fields() FieldDefinitionMap
- func (gt *Object) Interfaces() []*Interface
- func (gt *Object) Metadata() Metadata
- func (gt *Object) Name() string
- func (gt *Object) String() string
- type ObjectConfig
- type Output
- type Params
- type ParseFinishFunc
- type ParseLiteralFn
- type ParseValueFn
- type Plan
- type PlanCache
- type PlanCacheOptions
- type PlanResult
- type ResolveFieldFinishFunc
- type ResolveInfo
- type ResolveParams
- type ResolveTypeFn
- type ResolveTypeParams
- type ResponsePath
- type Result
- type Scalar
- func (st *Scalar) Description() string
- func (st *Scalar) Error() error
- func (st *Scalar) Metadata() Metadata
- func (st *Scalar) Name() string
- func (st *Scalar) ParseLiteral(valueAST ast.Value) interface{}
- func (st *Scalar) ParseValue(value interface{}) interface{}
- func (st *Scalar) Serialize(value interface{}) interface{}
- func (st *Scalar) String() string
- type ScalarConfig
- type Schema
- func (gq *Schema) AddExtensions(e ...Extension)
- func (gq *Schema) AddImplementation() error
- func (gq *Schema) AppendType(objectType Type) error
- func (gq *Schema) Directive(name string) *Directive
- func (gq *Schema) Directives() []*Directive
- func (gq *Schema) IsPossibleType(abstractType Abstract, possibleType *Object) bool
- func (gq *Schema) Metadata() Metadata
- func (gq *Schema) MutationType() *Object
- func (gq *Schema) PossibleTypes(abstractType Abstract) []*Object
- func (gq *Schema) QueryType() *Object
- func (gq *Schema) SubscriptionType() *Object
- func (gq *Schema) Type(name string) Type
- func (gq *Schema) TypeMap() TypeMap
- type SchemaConfig
- type SerializationConfig
- type SerializationError
- type SerializationErrorKind
- type SerializationMode
- type SerializeFn
- type SubscribeParams
- type Type
- type TypeInfo
- func (ti *TypeInfo) Argument() *Argument
- func (ti *TypeInfo) Directive() *Directive
- func (ti *TypeInfo) Enter(node ast.Node)
- func (ti *TypeInfo) FieldDef() *FieldDefinition
- func (ti *TypeInfo) InputType() Input
- func (ti *TypeInfo) Leave(node ast.Node)
- func (ti *TypeInfo) ParentType() Composite
- func (ti *TypeInfo) Type() Output
- type TypeInfoConfig
- type TypeMap
- type Union
- type UnionConfig
- type UnionTypesThunk
- type ValidationContext
- func (ctx *ValidationContext) Argument() *Argument
- func (ctx *ValidationContext) Directive() *Directive
- func (ctx *ValidationContext) Document() *ast.Document
- func (ctx *ValidationContext) Errors() []gqlerrors.FormattedError
- func (ctx *ValidationContext) FieldDef() *FieldDefinition
- func (ctx *ValidationContext) Fragment(name string) *ast.FragmentDefinition
- func (ctx *ValidationContext) FragmentSpreads(node *ast.SelectionSet) []*ast.FragmentSpread
- func (ctx *ValidationContext) InputType() Input
- func (ctx *ValidationContext) ParentType() Composite
- func (ctx *ValidationContext) RecursiveVariableUsages(operation *ast.OperationDefinition) []*VariableUsage
- func (ctx *ValidationContext) RecursivelyReferencedFragments(operation *ast.OperationDefinition) []*ast.FragmentDefinition
- func (ctx *ValidationContext) ReportError(err error)
- func (ctx *ValidationContext) Schema() *Schema
- func (ctx *ValidationContext) Type() Output
- func (ctx *ValidationContext) VariableUsages(node HasSelectionSet) []*VariableUsage
- type ValidationFinishFunc
- type ValidationResult
- type ValidationRuleFn
- type ValidationRuleInstance
- func ArgumentsOfCorrectTypeRule(context *ValidationContext) *ValidationRuleInstance
- func DefaultValuesOfCorrectTypeRule(context *ValidationContext) *ValidationRuleInstance
- func FieldsOnCorrectTypeRule(context *ValidationContext) *ValidationRuleInstance
- func FragmentsOnCompositeTypesRule(context *ValidationContext) *ValidationRuleInstance
- func KnownArgumentNamesRule(context *ValidationContext) *ValidationRuleInstance
- func KnownDirectivesRule(context *ValidationContext) *ValidationRuleInstance
- func KnownFragmentNamesRule(context *ValidationContext) *ValidationRuleInstance
- func KnownTypeNamesRule(context *ValidationContext) *ValidationRuleInstance
- func LoneAnonymousOperationRule(context *ValidationContext) *ValidationRuleInstance
- func NoFragmentCyclesRule(context *ValidationContext) *ValidationRuleInstance
- func NoUndefinedVariablesRule(context *ValidationContext) *ValidationRuleInstance
- func NoUnusedFragmentsRule(context *ValidationContext) *ValidationRuleInstance
- func NoUnusedVariablesRule(context *ValidationContext) *ValidationRuleInstance
- func OverlappingFieldsCanBeMergedRule(context *ValidationContext) *ValidationRuleInstance
- func PossibleFragmentSpreadsRule(context *ValidationContext) *ValidationRuleInstance
- func ProvidedNonNullArgumentsRule(context *ValidationContext) *ValidationRuleInstance
- func ScalarLeafsRule(context *ValidationContext) *ValidationRuleInstance
- func UniqueArgumentNamesRule(context *ValidationContext) *ValidationRuleInstance
- func UniqueFragmentNamesRule(context *ValidationContext) *ValidationRuleInstance
- func UniqueInputFieldNamesRule(context *ValidationContext) *ValidationRuleInstance
- func UniqueOperationNamesRule(context *ValidationContext) *ValidationRuleInstance
- func UniqueVariableNamesRule(context *ValidationContext) *ValidationRuleInstance
- func VariablesAreInputTypesRule(context *ValidationContext) *ValidationRuleInstance
- func VariablesInAllowedPositionRule(context *ValidationContext) *ValidationRuleInstance
- type VariableUsage
Examples ¶
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 unserializeDateTime(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, 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.
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.MustCompile("^[_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
Functions ¶
func CycleErrorMessage ¶
func DefaultResolveFn ¶ added in v0.7.2
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 ExecuteSubscription ¶ added in v0.9.0
func ExecuteSubscription(p ExecuteParams) chan *Result
ExecuteSubscription is similar to graphql.Execute but returns a channel instead of a Result currently does not support extensions
func IsAbstractType ¶ added in v0.5.0
func IsAbstractType(ttype interface{}) bool
func IsCompositeType ¶
func IsCompositeType(ttype interface{}) bool
IsCompositeType determines if given type is a GraphQLComposite type
func IsInputType ¶
IsInputType determines if given type is a GraphQLInputType
func IsLeafType ¶
IsLeafType determines if given type is a leaf value
func IsOutputType ¶
IsOutputType determines if given type is a GraphQLOutputType
func MetadataValue ¶ added in v0.13.0
MetadataValue returns the value of m stored under key as a T, and whether it is present with that type. A missing key and a value of another type both return the zero value of T and false.
func MisplaceDirectiveMessage ¶ added in v0.5.0
func NewLocatedErrorWithPath ¶ added in v0.7.6
func Subscribe ¶ added in v0.9.0
Subscribe performs a subscribe operation on the given query and schema To finish a subscription you can simply close the channel from inside the `Subscribe` function currently does not support extensions hooks
func UndefinedFieldMessage ¶
func UndefinedVarMessage ¶
func UnusedVariableMessage ¶
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 interface{} `json:"defaultValue"`
PrivateDescription string `json:"description"`
// Metadata is the metadata of the argument's ArgumentConfig.
Metadata Metadata `json:"-"`
}
func (*Argument) Description ¶
type ArgumentConfig ¶
type ArgumentState ¶ added in v0.12.0
type ArgumentState int
ArgumentState tells whether an argument, or a value inside it, was given in the operation.
const ( // ArgumentOmitted means the operation does not give the value. Args may // still hold a default value. ArgumentOmitted ArgumentState = iota // ArgumentNull means the operation gives an explicit null, as a literal // or through a variable. ArgumentNull // ArgumentSet means the operation gives a value. ArgumentSet )
func (ArgumentState) String ¶ added in v0.12.0
func (s ArgumentState) String() string
String returns "omitted", "null" or "set".
type CoercionConfig ¶ added in v0.12.0
type CoercionConfig struct {
Mode CoercionMode
// OnDifference, when set, is called in the report and spec modes for every
// value that differs between the legacy and spec rules. It may be called
// concurrently.
OnDifference func(ctx context.Context, d CoercionDifference)
}
CoercionConfig configures how a schema coerces input values.
type CoercionDifference ¶ added in v0.12.0
type CoercionDifference struct {
Kind CoercionDifferenceKind
// Path is the response path of the field.
Path []interface{}
ParentType string
FieldName string
// Argument is the path of the value inside the arguments, with strings for
// argument and input field names and ints for list indexes, such as
// ["input", "description"].
Argument []interface{}
// LegacyValue is the value in legacy mode, nil when it omits the key.
LegacyValue interface{}
// SpecValue is the value in spec mode, nil for an explicit null and for a
// rejected one.
SpecValue interface{}
}
CoercionDifference describes a value inside the arguments of a field that differs between the legacy and spec modes.
type CoercionDifferenceKind ¶ added in v0.12.0
type CoercionDifferenceKind int
CoercionDifferenceKind tells which rule makes a value differ between the legacy and spec modes.
const ( // CoercionNullDropped means an explicit null that legacy mode omits. CoercionNullDropped CoercionDifferenceKind = iota + 1 // CoercionNullDefaulted means an explicit null that legacy mode replaces // with the default value. CoercionNullDefaulted // CoercionDefaultApplied means a default value that spec mode applies to // an omitted value, such as an input field whose variable is not sent, // where legacy mode omits the key. CoercionDefaultApplied // CoercionNullRejected means a null in a non-null position, through a // variable with a default, that spec mode rejects with a field error // before the resolver runs, where legacy mode uses the default. CoercionNullRejected )
func (CoercionDifferenceKind) String ¶ added in v0.12.0
func (k CoercionDifferenceKind) String() string
String returns "null dropped", "null defaulted", "default applied" or "null rejected".
type CoercionMode ¶ added in v0.12.0
type CoercionMode int
CoercionMode selects whether input values are coerced with the legacy rules or with the rules of the GraphQL specification. The rules that differ are listed in CoercionDifferenceKind; the spec rules apply to ResolveParams.Args, while ResolveInfo.VariableValues keeps the legacy values.
const ( // CoercionLegacy keeps the historical rules, such as dropping an explicit // null from Args or replacing it with the default value. It is the // default. CoercionLegacy CoercionMode = iota // CoercionReport returns the same Args as CoercionLegacy and calls // CoercionConfig.OnDifference for every value that would differ in // CoercionSpec. CoercionReport // CoercionSpec coerces as the GraphQL specification and graphql-js do. For // example, an explicit null is a present key with a nil value, also inside // input objects, and default values apply only to omitted values. // // Enabling it changes Args for every resolver of the schema. Run // CoercionReport first to find the resolvers that are affected. CoercionSpec )
type Composite ¶
Composite interface for types that may describe the parent context of a selection set.
type Directive ¶
type Directive struct {
Name string `json:"name"`
Description string `json:"description"`
Locations []string `json:"locations"`
Args []*Argument `json:"args"`
// Metadata is the metadata of the directive's DirectiveConfig.
Metadata Metadata `json:"-"`
// 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 ¶ added in v0.5.0
type DirectiveConfig struct {
Name string `json:"name"`
Description string `json:"description"`
Locations []string `json:"locations"`
Args FieldConfigArgument `json:"args"`
// Metadata holds values for the application; it is not exposed in
// introspection.
Metadata Metadata `json:"-"`
}
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
}
var DirectiveLocationEnumType *Enum
DirectiveLocationEnumType is type definition for __DirectiveLocation
var TypeKindEnumType *Enum
TypeKindEnumType is type definition for __TypeKind
func NewEnum ¶
func NewEnum(config EnumConfig) *Enum
func (*Enum) Description ¶
func (*Enum) ParseLiteral ¶
func (*Enum) ParseValue ¶
func (gt *Enum) ParseValue(value interface{}) interface{}
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"`
// Metadata holds values for the application; it is not exposed in
// introspection.
Metadata Metadata `json:"-"`
}
type EnumValueConfig ¶
type EnumValueConfigMap ¶
type EnumValueConfigMap map[string]*EnumValueConfig
type EnumValueDefinition ¶
type ExecuteParams ¶
type ExecutionFinishFunc ¶ added in v0.9.0
type ExecutionFinishFunc func(*Result)
ExecutionFinishFunc is called when the execution is done
type Extension ¶ added in v0.9.0
type Extension interface {
// Init is used to help you initialize the extension
Init(context.Context, *Params) context.Context
// Name returns the name of the extension (make sure it's custom)
Name() string
// ParseDidStart is being called before starting the parse
ParseDidStart(context.Context) (context.Context, ParseFinishFunc)
// ValidationDidStart is called just before the validation begins
ValidationDidStart(context.Context) (context.Context, ValidationFinishFunc)
// ExecutionDidStart notifies about the start of the execution
ExecutionDidStart(context.Context) (context.Context, ExecutionFinishFunc)
// ResolveFieldDidStart notifies about the start of the resolving of a field
ResolveFieldDidStart(context.Context, *ResolveInfo) (context.Context, ResolveFieldFinishFunc)
// HasResult returns if the extension wants to add data to the result
HasResult() bool
// GetResult returns the data that the extension wants to add to the result
GetResult(context.Context) interface{}
}
Extension is an interface for extensions in graphql
type Field ¶
type Field struct {
Name string `json:"name"` // used by graphlql-relay
Type Output `json:"type"`
Args FieldConfigArgument `json:"args"`
Resolve FieldResolveFn `json:"-"`
Subscribe FieldResolveFn `json:"-"`
DeprecationReason string `json:"deprecationReason"`
Description string `json:"description"`
// Metadata holds values for the application; it is not exposed in
// introspection.
Metadata Metadata `json:"-"`
}
type FieldArgument ¶
type FieldConfigArgument ¶
type FieldConfigArgument map[string]*ArgumentConfig
func BindArg ¶ added in v0.7.0
func BindArg(obj interface{}, tags ...string) FieldConfigArgument
lazy way of binding args
type FieldDefinition ¶
type FieldDefinition struct {
Name string `json:"name"`
Description string `json:"description"`
Type Output `json:"type"`
Args []*Argument `json:"args"`
Resolve FieldResolveFn `json:"-"`
Subscribe FieldResolveFn `json:"-"`
DeprecationReason string `json:"deprecationReason"`
// Metadata is the metadata of the field's Field config.
Metadata Metadata `json:"-"`
}
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 ¶
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(p ResolveParams) (interface{}, error)
type FieldResolver ¶ added in v0.7.5
type FieldResolver interface {
// Resolve resolves the value for the given ResolveParams. It has the same semantics as FieldResolveFn.
Resolve(p ResolveParams) (interface{}, error)
}
FieldResolver is used in DefaultResolveFn when the the source value implements this interface.
type Fields ¶
func BindFields ¶ added in v0.7.0
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 ¶
type FieldsThunk func() Fields
type HasSelectionSet ¶
type HasSelectionSet interface {
GetKind() string
GetLoc() *ast.Location
GetSelectionSet() *ast.SelectionSet
}
type Input ¶
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) AddFieldConfig ¶ added in v0.7.6
func (gt *InputObject) AddFieldConfig(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) Metadata ¶ added in v0.13.0
func (gt *InputObject) Metadata() Metadata
Metadata returns the metadata given in the InputObject's config.
func (*InputObject) Name ¶
func (gt *InputObject) Name() string
func (*InputObject) String ¶
func (gt *InputObject) String() string
type InputObjectConfig ¶
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"`
// Metadata is the metadata of the field's InputObjectFieldConfig.
Metadata Metadata `json:"-"`
}
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 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 (*Interface) Description ¶
func (*Interface) Fields ¶
func (it *Interface) Fields() (fields FieldDefinitionMap)
type InterfaceConfig ¶
type InterfaceConfig struct {
Name string `json:"name"`
Fields interface{} `json:"fields"`
ResolveType ResolveTypeFn
Description string `json:"description"`
// Metadata holds values for the application; it is not exposed in
// introspection.
Metadata Metadata `json:"-"`
}
type InterfacesThunk ¶
type InterfacesThunk func() []*Interface
type IsTypeOfFn ¶
type IsTypeOfFn func(p IsTypeOfParams) bool
type IsTypeOfParams ¶ added in v0.5.0
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 ¶ added in v0.5.0
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 ¶
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 (*List) Description ¶
type Metadata ¶ added in v0.13.0
type Metadata struct {
// contains filtered or unexported fields
}
Metadata holds values that an application attaches to a schema element, for tooling, middleware or generic resolvers; it is the equivalent of extensions in graphql-js. The library does not interpret it, expose it in introspection or print it in SDL. Metadata is immutable and safe for concurrent use, and its zero value is empty. Empty Metadata values are all equal; non-empty ones are equal only when they come from the same call to NewMetadata.
func NewMetadata ¶ added in v0.13.0
NewMetadata returns Metadata holding a copy of values. The copy is shallow: the values themselves are shared, so values that resolvers may modify should not be stored. A nil or empty map gives the zero value.
Example ¶
A generic resolver reads the metadata of the type it returns to find where the data comes from, so the type's description stays free for documentation.
package main
import (
"encoding/json"
"fmt"
"github.com/gql-go/graphql"
)
func main() {
tables := map[string][]map[string]interface{}{
"books": {{"title": "Dune"}, {"title": "Emma"}},
"authors": {{"name": "Frank Herbert"}},
}
listResolver := func(p graphql.ResolveParams) (interface{}, error) {
table, ok := graphql.MetadataValue[string](p.Info.ReturnTypeMetadata(), "table")
if !ok {
return nil, fmt.Errorf("%s returns a type without a table", p.Info.FieldName)
}
return tables[table], nil
}
book := graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Description: "A book in the catalogue.",
Metadata: graphql.NewMetadata(map[string]interface{}{"table": "books"}),
Fields: graphql.Fields{"title": &graphql.Field{Type: graphql.String}},
})
author := graphql.NewObject(graphql.ObjectConfig{
Name: "Author",
Description: "A person who wrote books in the catalogue.",
Metadata: graphql.NewMetadata(map[string]interface{}{"table": "authors"}),
Fields: graphql.Fields{"name": &graphql.Field{Type: graphql.String}},
})
schema, _ := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"books": &graphql.Field{Type: graphql.NewList(book), Resolve: listResolver},
"authors": &graphql.Field{Type: graphql.NewList(author), Resolve: listResolver},
},
}),
})
result := graphql.Do(graphql.Params{Schema: schema, RequestString: `{ books { title } authors { name } }`})
out, _ := json.Marshal(result)
fmt.Println(string(out))
}
Output: {"data":{"authors":[{"name":"Frank Herbert"}],"books":[{"title":"Dune"},{"title":"Emma"}]}}
type Named ¶
type Named interface {
String() string
}
Named interface for types that do not include modifiers like List or NonNull.
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 (*NonNull) Description ¶
type Nullable ¶
type Nullable interface {
}
Nullable interface for types that can accept null as a value.
func GetNullable ¶
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 },
})
});
/
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 ¶
func NewObject(config ObjectConfig) *Object
func (*Object) AddFieldConfig ¶
func (*Object) Description ¶
func (*Object) Fields ¶
func (gt *Object) Fields() FieldDefinitionMap
func (*Object) Interfaces ¶
type ObjectConfig ¶
type ObjectConfig struct {
Name string `json:"name"`
Interfaces interface{} `json:"interfaces"`
Fields interface{} `json:"fields"`
IsTypeOf IsTypeOfFn `json:"isTypeOf"`
Description string `json:"description"`
// Metadata holds values for the application; it is not exposed in
// introspection.
Metadata Metadata `json:"-"`
}
type Params ¶
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 ParseFinishFunc ¶ added in v0.9.0
type ParseFinishFunc func(error)
ParseFinishFunc is called when the parse of the query is done
type ParseLiteralFn ¶
ParseLiteralFn is a function type for parsing the literal value of a GraphQLScalar type
type ParseValueFn ¶
type ParseValueFn func(value interface{}) interface{}
ParseValueFn is a function type for parsing the value of a GraphQLScalar type
type Plan ¶ added in v0.9.0
type Plan struct {
// contains filtered or unexported fields
}
Plan is a precomputed execution shape for a (schema, document, operationName) triple. Same triple → same Plan; cache + reuse.
PlanQuery does once-per-query work that Execute otherwise repeats every request: identify the operation, collect fragments, resolve every selection's *FieldDefinition, walk the selection tree to build per-level field lists, pre-coerce literal arguments, and evaluate @include/@skip (once per combination of the variables they use, when they use any). ExecutePlan walks the plan and only does work that's inherently per-request: variable substitution, abstract type runtime resolution, resolver invocation, and result materialization.
Plans are bound to the *Schema pointer they were planned against. If the schema is rebuilt, plans become stale (the *Schema pointer changes) and callers should re-plan.
func PlanQuery ¶ added in v0.9.0
PlanQuery walks the document, picks the named operation (or the only one), pre-resolves fragments + the entire selection tree, and returns a Plan ready to be executed against the same schema.
Errors are spec-aligned: missing operation name, unknown operation name, ambiguous operation, and document containing a non-operation non-fragment definition all surface here. Field-level errors (e.g. "no such field on type X") that the existing executor surfaces as dispatch-time errors continue to surface there — PlanQuery only fails on document-level errors.
type PlanCache ¶ added in v0.9.0
type PlanCache struct {
// contains filtered or unexported fields
}
PlanCache is a bounded, schema-aware LRU of parsed + validated + planned query state. Drop-in: a server's hot loop becomes
pr := cache.Get(schema, queryString, opName)
if len(pr.Errors) > 0 { return errorResponse(pr.Errors) }
args := mergeArgs(requestArgs, pr.SynthArgs)
result := graphql.ExecutePlan(pr.Plan, graphql.ExecuteParams{
Schema: *schema, Args: args, Context: ctx,
})
Each entry holds the *Plan plus any validation errors that arose at parse/validate/plan time. Entries are bound to the *Schema pointer they were planned against; on schema rebuild the *Schema pointer changes and stale entries fall out at lookup.
The cache is safe for concurrent use.
func NewPlanCache ¶ added in v0.9.0
func NewPlanCache(opts PlanCacheOptions) *PlanCache
NewPlanCache returns a PlanCache with the given options. Pass PlanCacheOptions{} to take all defaults.
func (*PlanCache) Get ¶ added in v0.9.0
func (c *PlanCache) Get(schema *Schema, query, operationName string) PlanResult
Get parses+validates+plans `query` against `schema`, or returns a cached entry if the query has been seen before with the same schema pointer.
Behavior on miss:
- Parse the query string. Parse errors → PlanResult{Errors}, no cache (parse failures are usually client bugs that don't repeat).
- (When opts.Normalize is true) rewrite leaf literal arguments into synth variables; the printed normalized doc becomes the cache key, so two queries that differ only in literal values collapse to one entry.
- Validate the (normalized) document against the schema. Validation errors → PlanResult{Errors}, cached so repeat-bad-queries don't hammer the validator.
- Plan the operation. Plan errors → cached as PlanResult{Errors}.
On a hit with normalize=true, the synthetic arguments extracted at THIS call's parse+normalize step are returned in PlanResult.SynthArgs; the cached *Plan itself is shared across all calls.
func (*PlanCache) HitsMisses ¶ added in v0.9.0
HitsMisses returns the cumulative hit and miss counts. Useful for surfacing as Prometheus counters.
type PlanCacheOptions ¶ added in v0.9.0
PlanCacheOptions tunes the cache. Zero values get sensible defaults. MaxEntries bounds the entry count (LRU eviction past it); MaxQueryBytes bypasses the cache for over-cap queries (large queries plus unbounded entry retention is the easy way to OOM a gateway). Normalize triggers literal→variable rewriting before hashing, so two queries that differ only in literal values collapse to one cache entry.
type PlanResult ¶ added in v0.9.0
type PlanResult struct {
Plan *Plan
SynthArgs map[string]interface{}
Errors []gqlerrors.FormattedError
}
PlanResult is what PlanCache.Get returns. On a successful build, Plan is non-nil and Errors is empty; on failure, Plan is nil and Errors holds the parse/validate/plan errors in the order they were detected. SynthArgs is populated when normalization extracted literals into synthetic variables — callers must merge it into the request's Args before ExecutePlan.
type ResolveFieldFinishFunc ¶ added in v0.9.0
type ResolveFieldFinishFunc func(interface{}, error)
ResolveFieldFinishFunc is called with the result of the ResolveFn and the error it returned
type ResolveInfo ¶
type ResolveInfo struct {
FieldName string
FieldASTs []*ast.Field
Path *ResponsePath
ReturnType Output
ParentType Composite
Schema Schema
Fragments map[string]ast.Definition
RootValue interface{}
Operation ast.Definition
VariableValues map[string]interface{}
}
func (ResolveInfo) FieldDefinition ¶ added in v0.13.0
func (info ResolveInfo) FieldDefinition() *FieldDefinition
FieldDefinition returns the definition of the field being resolved, looked up by FieldName on ParentType, so it also works on a ResolveInfo built outside execution. It returns nil when ParentType is nil, is not an object or interface, or has no such field, as for the introspection fields.
func (ResolveInfo) FieldMetadata ¶ added in v0.13.0
func (info ResolveInfo) FieldMetadata() Metadata
FieldMetadata returns the metadata of the field being resolved, or empty Metadata when FieldDefinition returns nil.
func (ResolveInfo) ReturnTypeMetadata ¶ added in v0.13.0
func (info ResolveInfo) ReturnTypeMetadata() Metadata
ReturnTypeMetadata returns the metadata of the named type the field returns, unwrapping List and NonNull, or empty Metadata when ReturnType is nil.
type ResolveParams ¶
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
// contains filtered or unexported fields
}
ResolveParams Params for FieldResolveFn()
func (ResolveParams) ArgumentState ¶ added in v0.12.0
func (p ResolveParams) ArgumentState(path ...interface{}) ArgumentState
ArgumentState reports whether the operation gives an argument, or a value inside it, and whether that value is null. The path starts with the argument name and continues with input field names (strings) and list indexes (ints), as in p.ArgumentState("input", "description"). The answer is the same in every CoercionMode and follows the specification: a variable that is not sent counts as omitted, and one that falls back to the default of its definition counts as given. A path that does not exist reports ArgumentOmitted.
It is computed when called. On a ResolveParams built outside execution it answers from Args.
type ResolveTypeFn ¶
type ResolveTypeFn func(p ResolveTypeParams) *Object
type ResolveTypeParams ¶ added in v0.5.0
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 ResponsePath ¶ added in v0.9.0
type ResponsePath struct {
Prev *ResponsePath
Key interface{}
}
func (*ResponsePath) AsArray ¶ added in v0.9.0
func (p *ResponsePath) AsArray() []interface{}
AsArray returns an array of path keys.
func (*ResponsePath) WithKey ¶ added in v0.9.0
func (p *ResponsePath) WithKey(key interface{}) *ResponsePath
WithKey returns a new responsePath containing the new key.
type Result ¶
type Result struct {
Data interface{} `json:"data"`
Errors []gqlerrors.FormattedError `json:"errors,omitempty"`
Extensions map[string]interface{} `json:"extensions,omitempty"`
}
Result has the response, errors and extensions from the resolved schema
func Execute ¶
func Execute(p ExecuteParams) (result *Result)
Execute runs an operation against a schema. Behavior is unchanged from prior releases: it now plans + executes via PlanQuery / ExecutePlan internally, but builds a fresh plan per call. Callers that issue the same query repeatedly should hold onto the *Plan returned by PlanQuery and pass it to ExecutePlan to skip the per-call planning work.
func ExecutePlan ¶ added in v0.9.0
func ExecutePlan(plan *Plan, p ExecuteParams) (result *Result)
ExecutePlan runs a planned operation. Args / Root / Context still flow in per-request; everything else (selection shape, field resolution, literal args, directive predicates, sub-plans) is taken from the plan.
The walker mirrors executor.executeOperation → executeFields → resolveField → completeValue, but skips collectFields and getFieldDef on the hot path. Per-field arguments come from the argPlan: static (no variables) bypasses getArgumentValues entirely.
func (*Result) ErrorsJoined ¶ added in v0.12.0
ErrorsJoined returns the errors in r.Errors combined with errors.Join, or nil when r is nil or has no errors. errors.Is and errors.As on the returned error reach each FormattedError and the errors it was built from, down to the error returned by the resolver, at any nesting depth.
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 (*Scalar) Description ¶
func (*Scalar) Metadata ¶ added in v0.13.0
Metadata returns the metadata given in the Scalar's config.
func (*Scalar) ParseLiteral ¶
func (*Scalar) ParseValue ¶
func (st *Scalar) ParseValue(value interface{}) interface{}
type ScalarConfig ¶
type ScalarConfig struct {
Name string `json:"name"`
Description string `json:"description"`
Serialize SerializeFn
ParseValue ParseValueFn
ParseLiteral ParseLiteralFn
// Metadata holds values for the application; it is not exposed in
// introspection.
Metadata Metadata `json:"-"`
}
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) AddExtensions ¶ added in v0.9.0
AddExtensions can be used to add additional extensions to the schema
func (*Schema) AddImplementation ¶ added in v0.7.1
Added Check implementation of interfaces at runtime.. Add Implementations at Runtime..
func (*Schema) AppendType ¶ added in v0.7.1
Edited. To check add Types at RunTime.. Append Runtime schema to typeMap
func (*Schema) Directives ¶
func (*Schema) IsPossibleType ¶ added in v0.5.0
func (*Schema) MutationType ¶
func (*Schema) PossibleTypes ¶ added in v0.5.0
func (*Schema) SubscriptionType ¶
type SchemaConfig ¶
type SchemaConfig struct {
Query *Object
Mutation *Object
Subscription *Object
Types []Type
Directives []*Directive
Extensions []Extension
// Serialization configures how values that cannot be serialized to the
// built-in scalars or to enums are handled. The default is lenient.
Serialization SerializationConfig
// Coercion configures whether input values reach ResolveParams.Args
// coerced with the legacy rules or with the rules of the specification.
// The default is the legacy rules.
Coercion CoercionConfig
// Metadata holds values for the application; it is not exposed in
// introspection.
Metadata Metadata
}
type SerializationConfig ¶ added in v0.11.0
type SerializationConfig struct {
Mode SerializationMode
// OnInvalidValue, when set, is called in the report and strict modes for
// every value that strict mode handles differently from lenient mode. It
// may be called concurrently.
OnInvalidValue func(ctx context.Context, err SerializationError)
}
SerializationConfig configures how a schema serializes values to the built-in scalars and to enums. Custom scalars are not checked.
type SerializationError ¶ added in v0.11.0
type SerializationError struct {
Kind SerializationErrorKind
// Path is the response path of the field, including list indexes.
Path []interface{}
ParentType string
FieldName string
// Type is the name of the scalar or enum type.
Type string
// Value is the value returned by the resolver.
Value interface{}
// Message follows graphql-js for invalid values and describes the change
// for corrected ones.
Message string
// LenientResult is the value that SerializationLenient returns.
LenientResult interface{}
// StrictResult is the value that SerializationStrict returns; nil for
// invalid values.
StrictResult interface{}
}
SerializationError describes a value that strict mode handles differently from lenient mode.
func (SerializationError) Error ¶ added in v0.11.0
func (e SerializationError) Error() string
Error returns the message.
type SerializationErrorKind ¶ added in v0.11.0
type SerializationErrorKind int
SerializationErrorKind tells what strict mode does with a value that it handles differently from lenient mode.
const ( // SerializationInvalid means the value has no valid serialization: strict // mode returns a field error. SerializationInvalid SerializationErrorKind = iota + 1 // SerializationCorrected means strict mode returns a valid serialization // that differs from the lenient result. SerializationCorrected )
func (SerializationErrorKind) String ¶ added in v0.11.0
func (k SerializationErrorKind) String() string
String returns "invalid" or "corrected".
type SerializationMode ¶ added in v0.11.0
type SerializationMode int
SerializationMode selects how values returned by resolvers are serialized to the built-in scalars (Int, Float, String, Boolean, ID) and to enums.
const ( // SerializationLenient keeps the historical behaviour: a value that cannot // be serialized becomes null or is converted as well as possible (for // example "12.50" becomes 12 for Int). It is the default. SerializationLenient SerializationMode = iota // SerializationReport returns the same result as SerializationLenient and // calls SerializationConfig.OnInvalidValue for every value that // SerializationStrict would handle differently. SerializationReport // SerializationStrict serializes values as the GraphQL specification and // graphql-js do: a value with a valid serialization returns it, and a value // without one becomes a field error. Values are unwrapped first: a // driver.Valuer becomes its value, and for String and ID an // encoding.TextMarshaler or fmt.Stringer becomes its text. // // Enabling it can change responses that are accepted today: a time.Time // becomes RFC 3339 instead of the fmt format, and values that lenient mode // returns as null or wrong (such as a valid null wrapper) return their // value. Run SerializationReport first and review the SerializationCorrected // and SerializationInvalid events before switching. SerializationStrict )
type SerializeFn ¶
type SerializeFn func(value interface{}) interface{}
SerializeFn is a function type for serializing a GraphQLScalar type value
type SubscribeParams ¶ added in v0.9.0
type SubscribeParams struct {
Schema Schema
RequestString string
RootValue interface{}
// ContextValue context.Context
VariableValues map[string]interface{}
OperationName string
FieldResolver FieldResolveFn
FieldSubscriber FieldResolveFn
}
SubscribeParams parameters for subscribing
type TypeInfo ¶
type TypeInfo struct {
// contains filtered or unexported fields
}
func NewTypeInfo ¶
func NewTypeInfo(opts *TypeInfoConfig) *TypeInfo
func (*TypeInfo) FieldDef ¶
func (ti *TypeInfo) FieldDef() *FieldDefinition
func (*TypeInfo) ParentType ¶
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 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 ¶
type UnionConfig ¶
type UnionConfig struct {
Name string `json:"name"`
Types interface{} `json:"types"`
ResolveType ResolveTypeFn
Description string `json:"description"`
// Metadata holds values for the application; it is not exposed in
// introspection.
Metadata Metadata `json:"-"`
}
type UnionTypesThunk ¶ added in v0.9.0
type UnionTypesThunk func() []*Object
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 *ast.SelectionSet) []*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 ValidationFinishFunc ¶ added in v0.9.0
type ValidationFinishFunc func([]gqlerrors.FormattedError)
ValidationFinishFunc is called when the Validation of the query is finished
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
}
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 ¶
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
concurrent-resolvers
command
|
|
|
context
command
|
|
|
crud
command
|
|
|
custom-scalar-type
command
|
|
|
hello-world
command
|
|
|
http
command
|
|
|
http-post
command
|
|
|
httpdynamic
command
|
|
|
modify-context
command
|
|
|
sql-nullstring
command
|
|
|
star-wars
command
|
|
|
todo
command
|
|
|
language
|
|
