graphql

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: May 5, 2024 License: MIT Imports: 18 Imported by: 3

Documentation

Index

Constants

View Source
const (
	SKIP    = "skip"
	INCLUDE = "include"
	IF      = "if"
)
View Source
const (
	DefaultMaxSubscriptions = 200
	DefaultMinRerunInterval = 5 * time.Second
)

Variables

This section is empty.

Functions

func CheckNonExpensive

func CheckNonExpensive(ctx context.Context) bool

func CreateConnection

func CreateConnection(ctx context.Context, socket JSONSocket, schema *Schema, opts ...ConnectionOption) *conn

func CreateJSONSocket

func CreateJSONSocket(ctx context.Context, socket JSONSocket, schema *Schema, makeCtx MakeCtxFunc, logger GraphqlLogger) *conn

CreateJSONSocket is deprecated. Consider using CreateConnection instead.

func CreateJSONSocketWithMutationSchema

func CreateJSONSocketWithMutationSchema(ctx context.Context, socket JSONSocket, schema, mutationSchema *Schema, makeCtx MakeCtxFunc, logger GraphqlLogger) *conn

CreateJSONSocketWithMutationSchema is deprecated. Consider using CreateConnection instead.

func ErrorCause

func ErrorCause(err error) error

func HTTPHandler

func HTTPHandler(schema *Schema, middlewares ...MiddlewareFunc) http.Handler

func HTTPHandlerWithExecutor

func HTTPHandlerWithExecutor(schema *Schema, executor ExecutorRunner, middlewares ...MiddlewareFunc) http.Handler

func Handler

func Handler(schema *Schema) http.Handler

func NewClientError

func NewClientError(format string, a ...interface{}) error

func NewSafeError

func NewSafeError(format string, a ...interface{}) error

func PrepareQuery

func PrepareQuery(ctx context.Context, typ Type, selectionSet *SelectionSet) error

PrepareQuery checks that the given selectionSet matches the schema typ, and parses the args in selectionSet

func SafeExecuteBatchResolver

func SafeExecuteBatchResolver(ctx context.Context, field *Field, sources []interface{}, args interface{}, selectionSet *SelectionSet) (results []interface{}, err error)

func SafeExecuteResolver

func SafeExecuteResolver(ctx context.Context, field *Field, source, args interface{}, selectionSet *SelectionSet) (result interface{}, err error)

func SanitizeError

func SanitizeError(err error) string

SanitizeError returns a sanitized error message for an error.

func ServeJSONSocket

func ServeJSONSocket(ctx context.Context, socket JSONSocket, schema *Schema, makeCtx MakeCtxFunc, logger GraphqlLogger)

ServeJSONSocket is deprecated. Consider using CreateConnection instead.

func ShouldIncludeNode

func ShouldIncludeNode(directives []*Directive) (bool, error)

ShouldIncludeNode validates and checks the value of a skip or include directive

func WrapAsSafeError

func WrapAsSafeError(err error, format string, a ...interface{}) error

WrapAsSafeError wraps an error into a "SafeError", and takes in a message. This message can be used like fmt.Sprintf to take in formatting and arguments.

Types

type AlwaysSpawnGoroutineFunc

type AlwaysSpawnGoroutineFunc func(context.Context, *Query) bool

type BatchResolver

type BatchResolver func(ctx context.Context, sources []interface{}, args interface{}, selectionSet *SelectionSet) ([]interface{}, error)

A BatchResolver calculates the value of a field for a slice of objects.

type ClientError

type ClientError SafeError

func (ClientError) Error

func (e ClientError) Error() string

func (ClientError) SanitizedError

func (e ClientError) SanitizedError() string

type ComputationInput

type ComputationInput struct {
	Id                   string
	Query                string
	ParsedQuery          *Query
	Variables            map[string]interface{}
	Ctx                  context.Context
	Previous             interface{}
	IsInitialComputation bool
	Extensions           map[string]interface{}
}

type ComputationOutput

type ComputationOutput struct {
	Metadata map[string]interface{}
	Current  interface{}
	Error    error
}

func RunMiddlewares

func RunMiddlewares(middlewares []MiddlewareFunc, input *ComputationInput) *ComputationOutput

type ConnectionOption

type ConnectionOption func(*conn)

func WithAlwaysSpawnGoroutineFunc

func WithAlwaysSpawnGoroutineFunc(fn AlwaysSpawnGoroutineFunc) ConnectionOption

func WithExecutionLogger

func WithExecutionLogger(logger GraphqlLogger) ConnectionOption

func WithExecutor

func WithExecutor(executor ExecutorRunner) ConnectionOption

func WithMakeCtx

func WithMakeCtx(makeCtx MakeCtxFunc) ConnectionOption

func WithMaxSubscriptions

func WithMaxSubscriptions(max int) ConnectionOption

func WithMinRerunInterval

func WithMinRerunInterval(d time.Duration) ConnectionOption

func WithMinRerunIntervalFunc

func WithMinRerunIntervalFunc(fn RerunIntervalFunc) ConnectionOption

WithMinRerunIntervalFunc is deprecated.

func WithMutationSchema

func WithMutationSchema(schema *Schema) ConnectionOption

func WithSubscriptionLogger

func WithSubscriptionLogger(logger SubscriptionLogger) ConnectionOption

type Directive

type Directive struct {
	Name string
	Args interface{}
}

A Directive can be attached to a field or fragment inclusion, and can affect execution of the query in any way the server desires.

The selections

users @skip(if:true)
drivers @include(if:true)

would skip the users selection and keep the drivers selection depending on the argument passed into the directive

type Enum

type Enum struct {
	Type       string
	Values     []string
	ReverseMap map[interface{}]string
}

Enum is a leaf value

func (*Enum) String

func (e *Enum) String() string

type Executor

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

BatchExecutor is a GraphQL executor. Given a query it can run through the execution of the request.

func (*Executor) Execute

func (e *Executor) Execute(ctx context.Context, typ Type, source interface{}, query *Query) (interface{}, error)

Execute executes a query by traversing the GraphQL query graph and resolving or executing fields. Any work that needs to be done is passed off to the scheduler to handle managing concurrency of the request. It must return a JSON marshallable response (or an error).

type ExecutorRunner

type ExecutorRunner interface {
	Execute(ctx context.Context, typ Type, source interface{}, query *Query) (interface{}, error)
}

func NewExecutor

func NewExecutor(scheduler WorkScheduler) ExecutorRunner

type Field

type Field struct {
	Resolve        Resolver
	BatchResolver  BatchResolver
	Type           Type
	Args           map[string]Type
	ParseArguments func(json interface{}) (interface{}, error)

	UseBatchFunc func(context.Context) bool
	Batch        bool
	External     bool
	Expensive    bool

	// NumParallelInvocationsFunc controls how many goroutines we'll create for a
	// field execution (batch or non-expensive).  We pass in the number of srcs
	// we're executing with so implementers can write custom logic.
	NumParallelInvocationsFunc func(ctx context.Context, numNodes int) int

	// FederatedKey tells us which services need this field as federated key.
	FederatedKey map[string]bool
}

Field knows how to compute field values of an Object

Fields are responsible for computing their value themselves.

type Fragment

type Fragment struct {
	On           string
	SelectionSet *SelectionSet
	Directives   []*Directive
}

A Fragment represents a reusable part of a GraphQL query

The On part of a Fragment represents the type of source object for which this Fragment should be used. That is not currently implemented in this package.

type GraphqlLogger

type GraphqlLogger interface {
	StartExecution(ctx context.Context, tags map[string]string, initial bool)
	FinishExecution(ctx context.Context, tags map[string]string, delay time.Duration)
	Error(ctx context.Context, err error, tags map[string]string)
}

type InputObject

type InputObject struct {
	Name        string
	InputFields map[string]Type
}

func (*InputObject) String

func (io *InputObject) String() string

type JSONSocket

type JSONSocket interface {
	ReadJSON(value interface{}) error
	WriteJSON(value interface{}) error
	Close() error
}

type List

type List struct {
	Type Type
}

List is a collection of other values

func (*List) String

func (l *List) String() string

type MakeCtxFunc

type MakeCtxFunc func(context.Context) context.Context

type MiddlewareFunc

type MiddlewareFunc func(input *ComputationInput, next MiddlewareNextFunc) *ComputationOutput

type MiddlewareNextFunc

type MiddlewareNextFunc func(input *ComputationInput) *ComputationOutput

type NonNull

type NonNull struct {
	Type Type
}

NonNull is a non-nullable other value

func (*NonNull) String

func (n *NonNull) String() string

type Object

type Object struct {
	Name        string
	Description string
	KeyField    *Field
	Fields      map[string]*Field
}

Object is a value with several fields

func (*Object) String

func (o *Object) String() string

type Query

type Query struct {
	Name string
	Kind string
	*SelectionSet
}

func MustParse

func MustParse(source string, vars map[string]interface{}) *Query

func Parse

func Parse(source string, vars map[string]interface{}) (*Query, error)

Parse parses an input GraphQL string into a *Query

Parse validates that the query looks syntactically correct and contains no cycles or unused fragments or immediate conflicts. However, it does not validate that the query is legal under a given schema, which instead is done by PrepareQuery.

type RerunIntervalFunc

type RerunIntervalFunc func(context.Context, *Query) time.Duration

type Resolver

type Resolver func(ctx context.Context, source, args interface{}, selectionSet *SelectionSet) (interface{}, error)

A Resolver calculates the value of a field of an object

type SafeError

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

func (SafeError) Error

func (e SafeError) Error() string

func (SafeError) Reason

func (e SafeError) Reason() string

func (SafeError) SanitizedError

func (e SafeError) SanitizedError() string

func (SafeError) Unwrap

func (e SafeError) Unwrap() error

Unwrap returns the wrapped error, implementing go's 1.13 error wrapping proposal.

type SanitizedError

type SanitizedError interface {
	error
	SanitizedError() string
}

type Scalar

type Scalar struct {
	Type      string
	Unwrapper func(interface{}) (interface{}, error)
}

Scalar is a leaf value. A custom "Unwrapper" can be attached to the scalar so it can have a custom unwrapping (if nil we will use the default unwrapper).

func (*Scalar) String

func (s *Scalar) String() string

type Schema

type Schema struct {
	Query    Type
	Mutation Type
}

type Selection

type Selection struct {
	Name         string
	Alias        string
	Args         interface{}
	SelectionSet *SelectionSet
	Directives   []*Directive

	// UnparsedArgs are the original json map[string]interface{} arguments.
	// This field is only available able after PrepareQuery has been called.
	UnparsedArgs map[string]interface{}

	// ParentType is the type that this field hangs off of.
	ParentType string
	// contains filtered or unexported fields
}

A selection represents a part of a GraphQL query

The selection

me: user(id: 166) { name }

has name "user" (representing the source field to be queried), alias "me" (representing the name to be used in the output), args id: 166 (representing arguments passed to the source field to be queried), and subselection name representing the information to be queried from the resulting object.

func Flatten

func Flatten(selectionSet *SelectionSet) ([]*Selection, error)

Flatten takes a SelectionSet and flattens it into an array of selections with unique aliases

A GraphQL query (the SelectionSet) is allowed to contain the same key multiple times, as well as fragments. For example,

{
  groups { name }
  groups { name id }
  ... on Organization { groups { widgets { name } } }
}

Flatten simplifies the query into an array of selections, merging fields, resulting in something like the new query

groups: { name name id { widgets { name } } }

Flatten does _not_ flatten out the inner queries, so the name above does not get flattened out yet.

type SelectionSet

type SelectionSet struct {
	Selections []*Selection
	Fragments  []*Fragment
}

SelectionSet represents a core GraphQL query

A SelectionSet can contain multiple fields and multiple fragments. For example, the query

{
  name
  ... UserFragment
  memberships {
    organization { name }
  }
}

results in a root SelectionSet with two selections (name and memberships), and one fragment (UserFragment). The subselection `organization { name }` is stored in the memberships selection.

Because GraphQL allows multiple fragments with the same name or alias, selections are stored in an array instead of a map.

func (*SelectionSet) ShallowCopy

func (s *SelectionSet) ShallowCopy() *SelectionSet

ShallowCopy returns a shallow copy of SelectionSet.

type SubscriptionLogger

type SubscriptionLogger interface {
	// Subscribe is called when a new subscription is started. Subscribe is not
	// called for queries that fail to parse or validate.
	Subscribe(ctx context.Context, id string, tags map[string]string)

	// Unsubscribe is called  when a subscription ends. It is guaranteed
	// to be called even if the subscription ends due to the connection closing.
	// The id argument corresponds to the id tag.
	Unsubscribe(ctx context.Context, id string)
}

type Type

type Type interface {
	String() string
	// contains filtered or unexported methods
}

Type represents a GraphQL type, and should be either an Object, a Scalar, or a List

type Union

type Union struct {
	Name        string
	Description string
	Types       map[string]*Object
}

Union is a option between multiple types

func (*Union) String

func (u *Union) String() string

type UnitResolver

type UnitResolver func(*WorkUnit) []*WorkUnit

UnitResolver is a function that executes a function and returns a set of new work units that need to be run.

type WorkScheduler

type WorkScheduler interface {
	Run(resolver UnitResolver, startingUnits ...*WorkUnit)
}

WorkScheduler is an interface that can be provided to the BatchExecutor to control how we traverse the Execution graph. Examples would include using a bounded goroutine pool, or using unbounded goroutine generation for each work unit.

func NewImmediateGoroutineScheduler

func NewImmediateGoroutineScheduler() WorkScheduler

NewImmediateGoroutineScheduler creates a new batch execution scheduler that executes all Units immediately in their own goroutine.

type WorkUnit

type WorkUnit struct {
	Ctx context.Context
	// contains filtered or unexported fields
}

WorkUnit is a set of execution work that will be done when running a graphql query. For every source there is an equivalent destination OutputNode that is used to record the result of running a section of the graphql query.

func (*WorkUnit) IsBatch

func (w *WorkUnit) IsBatch() bool

func (*WorkUnit) IsExpensive

func (w *WorkUnit) IsExpensive() bool

func (*WorkUnit) Selection

func (w *WorkUnit) Selection() *Selection

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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