gqlgen: github.com/99designs/gqlgen/graphql Index | Files | Directories

package graphql

import "github.com/99designs/gqlgen/graphql"

Index

Package Files

any.go bool.go cache.go context_field.go context_field_input.go context_operation.go context_response.go error.go executable_schema.go executable_schema_mock.go fieldset.go float.go handler.go id.go int.go jsonw.go map.go oneshot.go recovery.go response.go root.go stats.go string.go time.go upload.go version.go

Constants

const Version = "v0.12.1-dev"

Variables

var False = &lit{falseLit}
var Now = time.Now

Now is time.Now, except in tests. Then it can be whatever you want it to be.

var Null = &lit{nullLit}
var True = &lit{trueLit}

func AddError Uses

func AddError(ctx context.Context, err error)

AddError sends an error to the client, first passing it through the error presenter.

func AddErrorf Uses

func AddErrorf(ctx context.Context, format string, args ...interface{})

AddErrorf writes a formatted error to the client, first passing it through the error presenter.

func CollectAllFields Uses

func CollectAllFields(ctx context.Context) []string

CollectAllFields returns a slice of all GraphQL field names that were selected for the current resolver context. The slice will contain the unique set of all field names requested regardless of fragment type conditions.

func DefaultErrorPresenter Uses

func DefaultErrorPresenter(ctx context.Context, err error) *gqlerror.Error

func DefaultRecover Uses

func DefaultRecover(ctx context.Context, err interface{}) error

func GetErrors Uses

func GetErrors(ctx context.Context) gqlerror.List

func GetExtension Uses

func GetExtension(ctx context.Context, name string) interface{}

func GetExtensions Uses

func GetExtensions(ctx context.Context) map[string]interface{}

GetExtensions returns any extensions registered in the current result context

func GetFieldErrors Uses

func GetFieldErrors(ctx context.Context, rctx *FieldContext) gqlerror.List

GetFieldErrors returns a list of errors that occurred in the given field

func GetStartTime Uses

func GetStartTime(ctx context.Context) time.Time

GetStartTime should only be called by the handler package, it will be set into request context as Stats.Start

func HasFieldError Uses

func HasFieldError(ctx context.Context, rctx *FieldContext) bool

HasFieldError returns true if the given field has already errored

func HasOperationContext Uses

func HasOperationContext(ctx context.Context) bool

HasOperationContext checks if the given context is part of an ongoing operation

Some errors can happen outside of an operation, eg json unmarshal errors.

func Recover Uses

func Recover(ctx context.Context, err interface{}) (userMessage error)

func RegisterExtension Uses

func RegisterExtension(ctx context.Context, key string, value interface{})

RegisterExtension allows you to add a new extension into the graphql response

func StartOperationTrace Uses

func StartOperationTrace(ctx context.Context) context.Context

StartOperationTrace captures the current time and stores it in context. This will eventually be added to request context but we want to grab it as soon as possible. For transports that can only handle a single graphql query per http requests you dont need to call this at all, the server will do it for you. For transports that handle multiple (eg batching, subscriptions) this should be called before decoding each request.

func UnmarshalAny Uses

func UnmarshalAny(v interface{}) (interface{}, error)

func UnmarshalBoolean Uses

func UnmarshalBoolean(v interface{}) (bool, error)

func UnmarshalFloat Uses

func UnmarshalFloat(v interface{}) (float64, error)

func UnmarshalID Uses

func UnmarshalID(v interface{}) (string, error)

func UnmarshalInt Uses

func UnmarshalInt(v interface{}) (int, error)

func UnmarshalInt32 Uses

func UnmarshalInt32(v interface{}) (int32, error)

func UnmarshalInt64 Uses

func UnmarshalInt64(v interface{}) (int64, error)

func UnmarshalIntID Uses

func UnmarshalIntID(v interface{}) (int, error)

func UnmarshalMap Uses

func UnmarshalMap(v interface{}) (map[string]interface{}, error)

func UnmarshalString Uses

func UnmarshalString(v interface{}) (string, error)

func UnmarshalTime Uses

func UnmarshalTime(v interface{}) (time.Time, error)

func WithFieldContext Uses

func WithFieldContext(ctx context.Context, rc *FieldContext) context.Context

func WithFieldInputContext Uses

func WithFieldInputContext(ctx context.Context, fic *FieldInputContext) context.Context

func WithOperationContext Uses

func WithOperationContext(ctx context.Context, rc *OperationContext) context.Context

func WithResponseContext Uses

func WithResponseContext(ctx context.Context, presenterFunc ErrorPresenterFunc, recoverFunc RecoverFunc) context.Context

func WrapErrorWithInputPath Uses

func WrapErrorWithInputPath(ctx context.Context, err error) error

type Array Uses

type Array []Marshaler

func (Array) MarshalGQL Uses

func (a Array) MarshalGQL(writer io.Writer)

type Cache Uses

type Cache interface {
    // Get looks up a key's value from the cache.
    Get(ctx context.Context, key string) (value interface{}, ok bool)

    // Add adds a value to the cache.
    Add(ctx context.Context, key string, value interface{})
}

Cache is a shared store for APQ and query AST caching

type CollectedField Uses

type CollectedField struct {
    *ast.Field

    Selections ast.SelectionSet
}

func CollectFields Uses

func CollectFields(reqCtx *OperationContext, selSet ast.SelectionSet, satisfies []string) []CollectedField

CollectFields returns the set of fields from an ast.SelectionSet where all collected fields satisfy at least one of the GraphQL types passed through satisfies. Providing an empty or nil slice for satisfies will return collect all fields regardless of fragment type conditions.

func CollectFieldsCtx Uses

func CollectFieldsCtx(ctx context.Context, satisfies []string) []CollectedField

This is just a convenient wrapper method for CollectFields

type ErrorPresenterFunc Uses

type ErrorPresenterFunc func(ctx context.Context, err error) *gqlerror.Error

type ExecutableSchema Uses

type ExecutableSchema interface {
    Schema() *ast.Schema

    Complexity(typeName, fieldName string, childComplexity int, args map[string]interface{}) (int, bool)
    Exec(ctx context.Context) ResponseHandler
}

type ExecutableSchemaMock Uses

type ExecutableSchemaMock struct {
    // ComplexityFunc mocks the Complexity method.
    ComplexityFunc func(typeName string, fieldName string, childComplexity int, args map[string]interface{}) (int, bool)

    // ExecFunc mocks the Exec method.
    ExecFunc func(ctx context.Context) ResponseHandler

    // SchemaFunc mocks the Schema method.
    SchemaFunc func() *ast.Schema
    // contains filtered or unexported fields
}

ExecutableSchemaMock is a mock implementation of ExecutableSchema.

    func TestSomethingThatUsesExecutableSchema(t *testing.T) {

        // make and configure a mocked ExecutableSchema
        mockedExecutableSchema := &ExecutableSchemaMock{
            ComplexityFunc: func(typeName string, fieldName string, childComplexity int, args map[string]interface{}) (int, bool) {
	               panic("mock out the Complexity method")
            },
            ExecFunc: func(ctx context.Context) ResponseHandler {
	               panic("mock out the Exec method")
            },
            SchemaFunc: func() *ast.Schema {
	               panic("mock out the Schema method")
            },
        }

        // use mockedExecutableSchema in code that requires ExecutableSchema
        // and then make assertions.

    }

func (*ExecutableSchemaMock) Complexity Uses

func (mock *ExecutableSchemaMock) Complexity(typeName string, fieldName string, childComplexity int, args map[string]interface{}) (int, bool)

Complexity calls ComplexityFunc.

func (*ExecutableSchemaMock) ComplexityCalls Uses

func (mock *ExecutableSchemaMock) ComplexityCalls() []struct {
    TypeName        string
    FieldName       string
    ChildComplexity int
    Args            map[string]interface{}
}

ComplexityCalls gets all the calls that were made to Complexity. Check the length with:

len(mockedExecutableSchema.ComplexityCalls())

func (*ExecutableSchemaMock) Exec Uses

func (mock *ExecutableSchemaMock) Exec(ctx context.Context) ResponseHandler

Exec calls ExecFunc.

func (*ExecutableSchemaMock) ExecCalls Uses

func (mock *ExecutableSchemaMock) ExecCalls() []struct {
    Ctx context.Context
}

ExecCalls gets all the calls that were made to Exec. Check the length with:

len(mockedExecutableSchema.ExecCalls())

func (*ExecutableSchemaMock) Schema Uses

func (mock *ExecutableSchemaMock) Schema() *ast.Schema

Schema calls SchemaFunc.

func (*ExecutableSchemaMock) SchemaCalls Uses

func (mock *ExecutableSchemaMock) SchemaCalls() []struct {
}

SchemaCalls gets all the calls that were made to Schema. Check the length with:

len(mockedExecutableSchema.SchemaCalls())

type ExtendedError Uses

type ExtendedError interface {
    Extensions() map[string]interface{}
}

type FieldContext Uses

type FieldContext struct {
    Parent *FieldContext
    // The name of the type this field belongs to
    Object string
    // These are the args after processing, they can be mutated in middleware to change what the resolver will get.
    Args map[string]interface{}
    // The raw field
    Field CollectedField
    // The index of array in path.
    Index *int
    // The result object of resolver
    Result interface{}
    // IsMethod indicates if the resolver is a method
    IsMethod bool
}

func GetFieldContext Uses

func GetFieldContext(ctx context.Context) *FieldContext

func (*FieldContext) Path Uses

func (r *FieldContext) Path() ast.Path

type FieldInputContext Uses

type FieldInputContext struct {
    ParentField *FieldContext
    ParentInput *FieldInputContext
    Field       *string
    Index       *int
}

func GetFieldInputContext Uses

func GetFieldInputContext(ctx context.Context) *FieldInputContext

func NewFieldInputWithField Uses

func NewFieldInputWithField(field string) *FieldInputContext

func NewFieldInputWithIndex Uses

func NewFieldInputWithIndex(index int) *FieldInputContext

func (*FieldInputContext) Path Uses

func (fic *FieldInputContext) Path() ast.Path

type FieldInterceptor Uses

type FieldInterceptor interface {
    InterceptField(ctx context.Context, next Resolver) (res interface{}, err error)
}

FieldInterceptor called around each field

type FieldMiddleware Uses

type FieldMiddleware func(ctx context.Context, next Resolver) (res interface{}, err error)

type FieldSet Uses

type FieldSet struct {
    Values []Marshaler
    // contains filtered or unexported fields
}

func NewFieldSet Uses

func NewFieldSet(fields []CollectedField) *FieldSet

func (*FieldSet) Concurrently Uses

func (m *FieldSet) Concurrently(i int, f func() Marshaler)

func (*FieldSet) Dispatch Uses

func (m *FieldSet) Dispatch()

func (*FieldSet) MarshalGQL Uses

func (m *FieldSet) MarshalGQL(writer io.Writer)

type FieldStats Uses

type FieldStats struct {
    // When field execution started
    Started time.Time

    // When argument marshaling finished
    ArgumentsCompleted time.Time

    // When the field completed running all middleware. Not available inside field middleware!
    Completed time.Time
}

type GraphExecutor Uses

type GraphExecutor interface {
    CreateOperationContext(ctx context.Context, params *RawParams) (*OperationContext, gqlerror.List)
    DispatchOperation(ctx context.Context, rc *OperationContext) (ResponseHandler, context.Context)
    DispatchError(ctx context.Context, list gqlerror.List) *Response
}

type HandlerExtension Uses

type HandlerExtension interface {
    // ExtensionName should be a CamelCase string version of the extension which may be shown in stats and logging.
    ExtensionName() string
    // Validate is called when adding an extension to the server, it allows validation against the servers schema.
    Validate(schema ExecutableSchema) error
}

HandlerExtension adds functionality to the http handler. See the list of possible hook points below Its important to understand the lifecycle of a graphql request and the terminology we use in gqlgen before working with these

+--- REQUEST POST /graphql --------------------------------------------+ | +- OPERATION query OpName { viewer { name } } -----------------------+ | | | RESPONSE { "data": { "viewer": { "name": "bob" } } } | | | +- OPERATION subscription OpName2 { chat { message } } --------------+ | | | RESPONSE { "data": { "chat": { "message": "hello" } } } | | | | RESPONSE { "data": { "chat": { "message": "byee" } } } | | | +--------------------------------------------------------------------+ | +------------------------------------------------------------------------+

type MapCache Uses

type MapCache map[string]interface{}

MapCache is the simplest implementation of a cache, because it can not evict it should only be used in tests

func (MapCache) Add Uses

func (m MapCache) Add(ctx context.Context, key string, value interface{})

Add adds a value to the cache.

func (MapCache) Get Uses

func (m MapCache) Get(ctx context.Context, key string) (value interface{}, ok bool)

Get looks up a key's value from the cache.

type Marshaler Uses

type Marshaler interface {
    MarshalGQL(w io.Writer)
}

func MarshalAny Uses

func MarshalAny(v interface{}) Marshaler

func MarshalBoolean Uses

func MarshalBoolean(b bool) Marshaler

func MarshalFloat Uses

func MarshalFloat(f float64) Marshaler

func MarshalID Uses

func MarshalID(s string) Marshaler

func MarshalInt Uses

func MarshalInt(i int) Marshaler

func MarshalInt32 Uses

func MarshalInt32(i int32) Marshaler

func MarshalInt64 Uses

func MarshalInt64(i int64) Marshaler

func MarshalIntID Uses

func MarshalIntID(i int) Marshaler

func MarshalMap Uses

func MarshalMap(val map[string]interface{}) Marshaler

func MarshalString Uses

func MarshalString(s string) Marshaler

func MarshalTime Uses

func MarshalTime(t time.Time) Marshaler

func MarshalUpload Uses

func MarshalUpload(f Upload) Marshaler

type Mutation Uses

type Mutation struct{}

type NoCache Uses

type NoCache struct{}

func (NoCache) Add Uses

func (n NoCache) Add(ctx context.Context, key string, value interface{})

func (NoCache) Get Uses

func (n NoCache) Get(ctx context.Context, key string) (value interface{}, ok bool)

type OperationContext Uses

type OperationContext struct {
    RawQuery      string
    Variables     map[string]interface{}
    OperationName string
    Doc           *ast.QueryDocument

    Operation            *ast.OperationDefinition
    DisableIntrospection bool
    Recover              RecoverFunc
    ResolverMiddleware   FieldMiddleware

    Stats Stats
}

func GetOperationContext Uses

func GetOperationContext(ctx context.Context) *OperationContext

func (*OperationContext) Error Uses

func (c *OperationContext) Error(ctx context.Context, err error)

Error sends an error to the client, passing it through the formatter. Deprecated: use graphql.AddError(ctx, err) instead

func (*OperationContext) Errorf Uses

func (c *OperationContext) Errorf(ctx context.Context, format string, args ...interface{})

Errorf sends an error string to the client, passing it through the formatter. Deprecated: use graphql.AddErrorf(ctx, err) instead

func (*OperationContext) Validate Uses

func (c *OperationContext) Validate(ctx context.Context) error

type OperationContextMutator Uses

type OperationContextMutator interface {
    MutateOperationContext(ctx context.Context, rc *OperationContext) *gqlerror.Error
}

OperationContextMutator is called after creating the request context, but before executing the root resolver.

type OperationHandler Uses

type OperationHandler func(ctx context.Context) ResponseHandler

type OperationInterceptor Uses

type OperationInterceptor interface {
    InterceptOperation(ctx context.Context, next OperationHandler) ResponseHandler
}

OperationInterceptor is called for each incoming query, for basic requests the writer will be invoked once, for subscriptions it will be invoked multiple times.

type OperationMiddleware Uses

type OperationMiddleware func(ctx context.Context, next OperationHandler) ResponseHandler

type OperationParameterMutator Uses

type OperationParameterMutator interface {
    MutateOperationParameters(ctx context.Context, request *RawParams) *gqlerror.Error
}

OperationParameterMutator is called before creating a request context. allows manipulating the raw query on the way in.

type Query Uses

type Query struct{}

type RawParams Uses

type RawParams struct {
    Query         string                 `json:"query"`
    OperationName string                 `json:"operationName"`
    Variables     map[string]interface{} `json:"variables"`
    Extensions    map[string]interface{} `json:"extensions"`

    ReadTime TraceTiming `json:"-"`
}

func (*RawParams) AddUpload Uses

func (p *RawParams) AddUpload(upload Upload, key, path string) *gqlerror.Error

type RecoverFunc Uses

type RecoverFunc func(ctx context.Context, err interface{}) (userMessage error)

type RequestContext Uses

type RequestContext = OperationContext

Deprecated: Please update all references to OperationContext instead

func GetRequestContext Uses

func GetRequestContext(ctx context.Context) *RequestContext

Deprecated: Please update all references to GetOperationContext instead

type Resolver Uses

type Resolver func(ctx context.Context) (res interface{}, err error)

type ResolverContext Uses

type ResolverContext = FieldContext

Deprecated: Use FieldContext instead

func GetResolverContext Uses

func GetResolverContext(ctx context.Context) *ResolverContext

Deprecated: Use GetFieldContext instead

type Response Uses

type Response struct {
    Errors     gqlerror.List          `json:"errors,omitempty"`
    Data       json.RawMessage        `json:"data"`
    Extensions map[string]interface{} `json:"extensions,omitempty"`
}

Errors are intentionally serialized first based on the advice in https://github.com/facebook/graphql/commit/7b40390d48680b15cb93e02d46ac5eb249689876#diff-757cea6edf0288677a9eea4cfc801d87R107 and https://github.com/facebook/graphql/pull/384

func ErrorResponse Uses

func ErrorResponse(ctx context.Context, messagef string, args ...interface{}) *Response

type ResponseHandler Uses

type ResponseHandler func(ctx context.Context) *Response

func OneShot Uses

func OneShot(resp *Response) ResponseHandler

type ResponseInterceptor Uses

type ResponseInterceptor interface {
    InterceptResponse(ctx context.Context, next ResponseHandler) *Response
}

ResponseInterceptor is called around each graphql operation response. This can be called many times for a single operation the case of subscriptions.

type ResponseMiddleware Uses

type ResponseMiddleware func(ctx context.Context, next ResponseHandler) *Response

type Stats Uses

type Stats struct {
    OperationStart time.Time
    Read           TraceTiming
    Parsing        TraceTiming
    Validation     TraceTiming
    // contains filtered or unexported fields
}

func (*Stats) GetExtension Uses

func (c *Stats) GetExtension(name string) interface{}

func (*Stats) SetExtension Uses

func (c *Stats) SetExtension(name string, data interface{})

type Status Uses

type Status int

type Subscription Uses

type Subscription struct{}

type TraceTiming Uses

type TraceTiming struct {
    Start time.Time
    End   time.Time
}

type Transport Uses

type Transport interface {
    Supports(r *http.Request) bool
    Do(w http.ResponseWriter, r *http.Request, exec GraphExecutor)
}

Transport provides support for different wire level encodings of graphql requests, eg Form, Get, Post, Websocket

type Unmarshaler Uses

type Unmarshaler interface {
    UnmarshalGQL(v interface{}) error
}

type Upload Uses

type Upload struct {
    File        io.Reader
    Filename    string
    Size        int64
    ContentType string
}

func UnmarshalUpload Uses

func UnmarshalUpload(v interface{}) (Upload, error)

type WriterFunc Uses

type WriterFunc func(writer io.Writer)

func (WriterFunc) MarshalGQL Uses

func (f WriterFunc) MarshalGQL(w io.Writer)

Directories

PathSynopsis
errcode
executor
executor/testexecutor
handler
handler/apollotracing
handler/debug
handler/extension
handler/lru
handler/testserver
handler/transport
introspectionintrospection implements the spec defined in https://github.com/facebook/graphql/blob/master/spec/Section%204%20--%20Introspection.md#schema-introspection
playground

Package graphql imports 14 packages (graph) and is imported by 202 packages. Updated 2020-08-14. Refresh now. Tools for package owners.