gqlengine

package module
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2020 License: Apache-2.0 Imports: 25 Imported by: 0

README

GQLEngine is the best productive solution for implementing a graphql server for highest formance

examples

Getting started

Get the module:

go get -u github.com/gqlengine/gqlengine

main.go

package main

import (
  "net/http"

  "github.com/gqlengine/gqlengine"
)

func main() {
  engine := gqlengine.NewEngine(gqlengine.Options{
	Tracing: true, // enable tracing extensions
  })
  
  // register your queries, mutations and subscriptions
  engine.NewQuery(mySimpleQuery)
  
  // do NOT forget init the engine
  if err := engine.Init(); err != nil {
    panic(err)
  }
  
  // serve for HTTP
  http.HandleFunc("/api/graphql", engine.ServeHTTP)
  if err := http.ListenAndServe(":8000", nil); err != nil {
    panic(err)
  }
}

api.go

package main

type MyInfo struct {
  gqlengine.IsGraphQLObject `gqlDesc:"my info"`
  SaySomething string
}

func mySimpleQuery() error {
  panic("not implemented")
}

use playground

go get -u github.com/gqlengine/playground

update the code


...

import (
  "github.com/gorilla/mux"
  "github.com/gqlengine/playground"
)

...

func main() {
  
  ... // init your gql engine
  
  playground.SetEndpoints("/api/graphql", "/api/graphql/subscriptions")
  
  // recommends to use 'gorilla/mux' to serve the playground web assets
  r := mux.NewRouter()
  r.HandleFunc("/api/graphql", engine.ServeHTTP)
  r.HandleFunc("/api/graphql/subscriptions", engine.ServeWebsocket)
  r.PathPrefix("/api/graphql/playground").
    Handler(http.StripPrefix("/api/graphql/playground",
      http.FileServer(playground.WebBundle)))

  println("open playground http://localhost:9996/api/graphql/playground/")
  if err := http.ListenAndServe(":9996", r); err != nil {
    panic(err)
  }
}

open browser, you can get the playground all in box

Features

  • Basic features
    • Object type reflection
    • Interface pre-register
    • Union pre-register
    • Enum reflection
    • Scalar reflection
    • Input reflection
    • Arguments reflection
  • Subscription (Integerates Websocket)
  • Multipart Upload (Upload images/files in graphql query)
  • Custom ID
  • Tracing extensions
  • document tags
  • operation hijacking

Documentation

Overview

Copyright 2020 凯斐德科技(杭州)有限公司 (Karfield Technology, ltd.)

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const (
	ContentTypeJSON           = "application/json"
	ContentTypeGraphQL        = "application/graphql"
	ContentTypeFormURLEncoded = "application/x-www-form-urlencoded"
	ContextTypeMultipart      = "multipart/form-data"
)
View Source
const (
	DefaultMultipartParsingBufferSize = 10 * 1024 * 1024
)

Variables

View Source
var Duration = graphql.NewScalar(graphql.ScalarConfig{
	Name:        "Duration",
	Description: "time duration",
	Serialize: func(value interface{}) interface{} {
		switch value := value.(type) {
		case time.Duration:
			return value.String()
		case *time.Duration:
			return value.String()
		}
		return nil
	},
	ParseValue: func(value interface{}) interface{} {
		switch value := value.(type) {
		case string:
			d, _ := time.ParseDuration(value)
			return d
		case *string:
			d, _ := time.ParseDuration(*value)
			return d
		}
		return nil
	},
	ParseLiteral: func(valueAST ast.Value) interface{} {
		switch valueAST := valueAST.(type) {
		case *ast.StringValue:
			d, _ := time.ParseDuration(valueAST.Value)
			return d
		}
		return nil
	},
})
View Source
var UploadScalar = graphql.NewScalar(graphql.ScalarConfig{
	Name:        "Upload",
	Description: "The `Upload` scalar type represents a file upload.",
	Serialize: func(value interface{}) interface{} {
		panic("Upload serialization unsupported.")
		return nil
	},
	ParseValue: func(value interface{}) interface{} {
		return value
	},
	ParseLiteral: func(valueAST ast.Value) interface{} {
		panic("Upload literal unsupported.")
	},
})
View Source
var Void = graphql.NewScalar(graphql.ScalarConfig{
	Name:         "Void",
	Description:  "void",
	Serialize:    func(value interface{}) interface{} { return "0" },
	ParseValue:   func(value interface{}) interface{} { return 0 },
	ParseLiteral: func(valueAST ast.Value) interface{} { return 0 },
})

Functions

func BeforeResolve

func BeforeResolve(resolve interface{}, checker interface{}) (interface{}, error)

func HandleHTTPOptions

func HandleHTTPOptions(w http.ResponseWriter, r *http.Request)

Types

type Arguments

type Arguments interface {
	GraphQLArguments()
}

type ContextError

type ContextError interface {
	gqlerrors.ExtendedError
	StatusCode() int
}

type CustomParserInput

type CustomParserInput interface {
	Input
	GraphQLInputParseValue(map[string]interface{}) interface{}
}

type Engine

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

func NewEngine

func NewEngine(options Options) *Engine

func (*Engine) AddMutation

func (engine *Engine) AddMutation(resolve interface{}, name string, description string, tags ...string) error

func (*Engine) AddQuery

func (engine *Engine) AddQuery(resolve interface{}, name string, description string, tags ...string) error

func (*Engine) AddSubscription

func (engine *Engine) AddSubscription(onSubscribed, onUnsubscribed interface{}, name string, description string, tags ...string) error

func (*Engine) AddSubscriptionAuthentication

func (engine *Engine) AddSubscriptionAuthentication(auth func(authToken string) (context.Context, error))

func (*Engine) Init

func (engine *Engine) Init() (err error)

func (*Engine) NewMutation

func (engine *Engine) NewMutation(resolve interface{}) MutationBuilder

func (*Engine) NewQuery

func (engine *Engine) NewQuery(resolve interface{}) QueryBuilder

func (*Engine) NewSubscription

func (engine *Engine) NewSubscription(onSubscribed interface{}) SubscriptionBuilder

func (*Engine) PreRegisterInterface

func (engine *Engine) PreRegisterInterface(interfacePrototype, modelPrototype interface{}) error

func (*Engine) PreRegisterUnion

func (engine *Engine) PreRegisterUnion(interfacePrototype interface{}, types ...interface{}) error

func (*Engine) RegisterEnum

func (engine *Engine) RegisterEnum(prototype interface{}) (*graphql.Enum, error)

func (*Engine) RegisterInput

func (engine *Engine) RegisterInput(prototype interface{}) (*graphql.InputObject, error)

func (*Engine) RegisterObject

func (engine *Engine) RegisterObject(prototype interface{}) (*graphql.Object, error)

func (*Engine) RegisterPlugin

func (engine *Engine) RegisterPlugin(name string, plugin Plugin)

func (*Engine) RegisterScalar

func (engine *Engine) RegisterScalar(prototype interface{}) (*graphql.Scalar, error)

func (*Engine) RegisterType

func (engine *Engine) RegisterType(prototype interface{}) (graphql.Type, error)

func (*Engine) Schema

func (engine *Engine) Schema() graphql.Schema

func (*Engine) ServeHTTP

func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Engine) ServeWebsocket

func (engine *Engine) ServeWebsocket(w http.ResponseWriter, r *http.Request)

type Enum

type Enum interface {
	GraphQLEnumDescription() string
	GraphQLEnumValues() EnumValueMapping
}

type EnumValue

type EnumValue struct {
	Value       interface{}
	Description string
}

type EnumValueMapping

type EnumValueMapping map[string]EnumValue

type Error

type Error interface {
	error
	GraphQLErrorExtension() string
}

type FastRequestContext

type FastRequestContext interface {
	RequestContext
	GraphQLContextFromFastHTTPRequest(ctx *fasthttp.RequestCtx) error
}

type FastResponseContext

type FastResponseContext interface {
	ResponseContext
	GraphQLContextToFastHTTPResponse(ctx *fasthttp.RequestCtx) error
}

type FieldSelection

type FieldSelection interface {
	IsSelected(fieldNames ...string) bool
}

type ID

type ID interface {
	GraphQLID()
}

type Input

type Input interface {
	GraphQLInputDescription() string
}

type Interface

type Interface interface {
	GraphQLInterfaceDescription() string
}

type IsGraphQLArguments

type IsGraphQLArguments struct{}

type IsGraphQLInput

type IsGraphQLInput struct{}

type IsGraphQLInterface

type IsGraphQLInterface struct{}

type IsGraphQLObject

type IsGraphQLObject struct{}

type MutationBuilder

type MutationBuilder interface {
	Name(name string) MutationBuilder
	Description(desc string) MutationBuilder
	Tags(tags ...string) MutationBuilder
	WrapWith(fn interface{}) MutationBuilder
}

type NameAlterableEnum

type NameAlterableEnum interface {
	Enum
	GraphQLEnumName() string
}

type NameAlterableInput

type NameAlterableInput interface {
	Input
	GraphQLInputName() string
}

type NameAlterableInterface

type NameAlterableInterface interface {
	Interface
	GraphQLInterfaceName() string
}

type NameAlterableObject

type NameAlterableObject interface {
	Object
	GraphQLObjectName() string
}

type NameAlterableScalar

type NameAlterableScalar interface {
	Scalar
	GraphQLScalarName() string
}

type Object

type Object interface {
	GraphQLObjectDescription() string
}

type ObjectDelegation

type ObjectDelegation interface {
	Object
	GraphQLObjectDelegation() interface{}
}

type Options

type Options struct {
	Debug                      bool
	Tracing                    bool
	WsSubProtocol              string
	Tags                       bool
	MultipartParsingBufferSize int64
}

type Plugin

type Plugin interface {
	BeforeCheckArgumentsStruct(baseType reflect.Type) interface{}
	CheckArgumentsEmbeddedField(pluginData interface{}, field *reflect.StructField) error
	CheckArgument(pluginData interface{}, name string, typ graphql.Type, tag *reflect.StructTag, goType reflect.Type, defaultValue interface{}) error
	MatchAndCallArgumentsMethod(pluginData interface{}, method reflect.Method, prototype reflect.Value) error
	AfterCheckArgumentsStruct(pluginData interface{}) error

	BeforeCheckObjectStruct(baseType reflect.Type) interface{}
	CheckObjectEmbeddedFieldTags(pluginData interface{}, field *reflect.StructField) error
	CheckObjectField(pluginData interface{}, name string, typ graphql.Type, tag *reflect.StructTag, goType reflect.Type) error
	MatchAndCallObjectMethod(pluginData interface{}, method reflect.Method, prototype reflect.Value) error
	AfterCheckObjectStruct(pluginData interface{}, obj *graphql.Object) error

	BeforeCheckInputStruct(baseType reflect.Type) interface{}
	CheckInputObjectEmbeddedFieldTags(pluginData interface{}, field *reflect.StructField) error
	CheckInputObjectField(pluginData interface{}, name string, typ graphql.Type, tag *reflect.StructTag, goType reflect.Type) error
	MatchAndCallInputObjectMethod(pluginData interface{}, method reflect.Method, prototype reflect.Value) error
	AfterCheckInputStruct(pluginData interface{}, input *graphql.InputObject) error

	CheckQueryOperation(operation string, arguments reflect.Type, typ reflect.Type)
	CheckMutationOperation(operation string, arguments reflect.Type, typ reflect.Type)
}

type QueryBuilder

type QueryBuilder interface {
	Name(name string) QueryBuilder
	Description(desc string) QueryBuilder
	Tags(tags ...string) QueryBuilder
	WrapWith(fn interface{}) QueryBuilder
}

type RequestContext

type RequestContext interface {
	GraphQLContextFromHTTPRequest(r *http.Request) error
}

type RequestContextBeforeCalled

type RequestContextBeforeCalled interface {
	RequestContext
	GraphQLCheckErrorBeforeCalled() error
}

type RequestOptions

type RequestOptions struct {
	Query         string                 `json:"query" url:"query" schema:"query"`
	Variables     map[string]interface{} `json:"variables" url:"variables" schema:"variables"`
	OperationName string                 `json:"operationName" url:"operationName" schema:"operationName"`
}

type ResponseContext

type ResponseContext interface {
	GraphQLContextToHTTPResponse(w http.ResponseWriter) error
}

type Scalar

type Scalar interface {
	GraphQLScalarSerialize() interface{}
	GraphQLScalarParseValue(value interface{})
	GraphQLScalarDescription() string
}

type ScalarWithASTParsing

type ScalarWithASTParsing interface {
	Scalar
	GraphQLScalarParseLiteral(valueAST ast.Value)
}

type Subscription

type Subscription interface {
	Available() bool
	SendData(data interface{}) error
	Close() error
}

type SubscriptionBuilder

type SubscriptionBuilder interface {
	Name(name string) SubscriptionBuilder
	Description(desc string) SubscriptionBuilder
	OnUnsubscribed(unsubscribed interface{}) SubscriptionBuilder
	Tags(tags ...string) SubscriptionBuilder
	WrapWith(fn interface{}) SubscriptionBuilder
}

type SubscriptionSession

type SubscriptionSession interface {
	GraphQLSubscriptionSession()
}

type Tracing

type Tracing struct {
	Version    int              `json:"version"`
	StartTime  time.Time        `json:"startTime"`
	EndTime    time.Time        `json:"endTime"`
	Duration   int64            `json:"duration"`
	Parsing    TracingRecord    `json:"parsing"`
	Validation TracingRecord    `json:"validation"`
	Execution  TracingExecution `json:"execution"`
}

type TracingExecution

type TracingExecution struct {
	TracingRecord
	Resolvers []*TracingResolveRecord `json:"resolvers"`
}

type TracingRecord

type TracingRecord struct {
	StartOffset int64 `json:"startOffset"`
	Duration    int64 `json:"duration"`
}

type TracingResolveRecord

type TracingResolveRecord struct {
	TracingRecord
	Path       []interface{} `json:"path"`
	ParentType string        `json:"parentType"`
	FieldName  string        `json:"fieldName"`
	ReturnType string        `json:"returnType"`
}

type Upload

type Upload struct {
	*multipart.FileHeader
}

Jump to

Keyboard shortcuts

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