gqlgo

package module
v0.0.0-...-02319f8 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2020 License: Apache-2.0 Imports: 17 Imported by: 0

README

GQLGo

An open and well design GraphQL Client for Gophers, it's going to be great.
And welcome issue and PR by the way.

Features

  • GraphQL
    • basis request
    • batch requests
    • error handling
    • subscriptions
    • file upload
  • Custom HTTP Header

Usage

You can check example faster to make the program run.

Install
go get -u github.com/poohvpn/gqlgo
Create Client
client := gqlgo.NewClient(`https://some_endpoint`)
// or
client := gqlgo.NewClient(`https://some_endpoint`, gqlgo.Option{
	HTTPClient: myHttpClient,
	BearerAuth: "token",
	Headers: ...,
	WebSocketEndpoint: "wss://some_endpoint",
})
Do a GraphQL Request
res := struct {
	User struct {
		ID   string `json:"id"`
		Name string `json:"name"`
		Email string `json:"email"`
	} `json:"User"`
}{}
err := client.Do(context.Background(), &res, gqlgo.Request{
	Query: `
query ($id:ID){
	User (id: $id) {
		id
		name
		email
	}
}
`,
	Variables: map[string]interface{}{
		"id": "...",
	},
})
GraphQL error handling
detailErr := &gqlgo.DetailError{}
gqlErr := gqlgo.GraphQLErrors{}
switch {
case err == nil:
case errors.As(err, &detailErr):
	fmt.Println("detail error:", detailErr.Response.StatusCode, "\n", detailErr.Content)
	return
case errors.As(err, &gqlErr):
	gqlOneErr := gqlErr[0]
	fmt.Println("graphql server error:",
		gqlOneErr.Message,
		"on line",
		gqlOneErr.Locations[0].Line,
		"column",
		gqlOneErr.Locations[0].Column,
	)
	return
default:
	fmt.Println("graphql client error:", err.Error())
	return
}
Batch Requests
req1 := gqlgo.Request{...}
req2 := gqlgo.Request{...}
data := []interface{}{&data1, &data2}
err := client.Do(context.Background(), data, req1, req2)
Subscription
req1 := gqlgo.Request{...}
subId,err := client.Subscribe(req, func(data json.RawMessage, errors gqlgo.GraphQLErrors, completed bool) error {
	...
})

Credits

GraphQL Spec
GraphQL MultiPart Request Spec
Thanks to machinebox/graphql, learning a lot from it.
apollographql/subscriptions-transport-ws

License

Apache License 2.0
Copyright 2020 PoohVPN

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	*Option
	WebSocketClient *WSClient
}

func NewClient

func NewClient(endpoint string, opt ...Option) *Client

NewClient only take the first Option if given

func (*Client) Do

func (c *Client) Do(ctx context.Context, res interface{}, requests ...Request) error

func (*Client) Subscribe

func (c *Client) Subscribe(req Request, handler SubscriptionHandler) (id string, err error)

func (*Client) Unsubscribe

func (c *Client) Unsubscribe(id string) error

type DetailError

type DetailError struct {
	OriginError error
	Content     string
	Response    *http.Response
}

func (*DetailError) Error

func (e *DetailError) Error() string

type File

type File struct {
	Reader io.Reader
	Name   string
}

type GraphQLError

type GraphQLError struct {
	Message    string                 `json:"message,omitempty"`
	Locations  []GraphQLErrorLocation `json:"locations,omitempty"`
	Path       []interface{}          `json:"path,omitempty"`
	Extensions map[string]interface{} `json:"extensions,omitempty"`
}

Path element's type should be either string or int, according to the samples of http://spec.graphql.org/draft/#sec-Errors

func (*GraphQLError) Error

func (e *GraphQLError) Error() string

type GraphQLErrorLocation

type GraphQLErrorLocation struct {
	Line   int `json:"line"`
	Column int `json:"column"`
}

type GraphQLErrors

type GraphQLErrors []GraphQLError

func (GraphQLErrors) Error

func (e GraphQLErrors) Error() string

type Option

type Option struct {
	// Endpoint means HTTP server URL
	Endpoint string

	// HTTPClient specify http client, when it's nil, GraphQL client will use http.DefaultClient
	// HTTPClient should not change to nil after init
	HTTPClient *http.Client

	// Headers apply to http request every time at the beginning
	Headers map[string]string

	// CloseBody will close http request body immediately for reusing of http client
	CloseBody bool

	// Client will add Header "Authorization: Bearer <Token>" for every request when BearerAuth is not empty
	BearerAuth string

	// Custom HTTP Log func like func(s string) { fmt.Println(s) }
	Log func(msg string)

	// NotCheckHTTPStatusCode200 disable http response status code for some irregular GraphQL Servers
	NotCheckHTTPStatusCode200 bool

	// WebSocketEndpoint specify websocket endpoint, default is Endpoint's websocket schema
	WebSocketEndpoint string

	// WebSocketOption specify websocket client option
	WebSocketOption WSOption
}

Option be changed at anytime after NewClient

type Request

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

	// Headers apply to http request at last phase of assembling http request.
	Headers map[string]string `json:"-"`
}

type SubscriptionHandler

type SubscriptionHandler func(rawMsg json.RawMessage, gqlErrs GraphQLErrors, completed bool) error

GQL_ERROR will be appended to errors, then errors will be a list that contains only one error. completed is true only happens to GraphQL server send completed, if completed is true, data and errors must be nil. when returned error is not nil, Subscription will be unsubscribed. SubscriptionHandler is executed synchronized, return as soon as possible

type WSClient

type WSClient struct {
	*WSOption
	// contains filtered or unexported fields
}

func NewWSClient

func NewWSClient(endpoint string, opt ...WSOption) *WSClient

func (*WSClient) Close

func (c *WSClient) Close() error

func (*WSClient) Subscribe

func (c *WSClient) Subscribe(req Request, handler SubscriptionHandler) (id string, err error)

func (*WSClient) UnderlyingConn

func (c *WSClient) UnderlyingConn() *websocket.Conn

func (*WSClient) Unsubscribe

func (c *WSClient) Unsubscribe(id string) error

func (*WSClient) UnsubscribeAll

func (c *WSClient) UnsubscribeAll() error

type WSOption

type WSOption struct {
	// Dialer specify websocket Dialer, default is using websocket.DefaultDialer
	Dialer *websocket.Dialer

	// Headers apply to http request
	Headers map[string]string

	// disable automatic reconnecting
	NotReconnect bool

	// ReconnectAttempts is the maximum attempts of reconnection after connected, default is math.MaxUint32
	ReconnectAttempts uint32

	// KeepAliveTimeout is the timeout of server keepalive since last keepalive message.
	// Default is 30 seconds, less or equal than 10 second will disable checking keepalive timeout.
	KeepAliveTimeout time.Duration

	// Custom WebSocket GraphQL Log func like func(s string) { fmt.Println(s) }
	Log func(msg string)
}

Option be changed at anytime after NewWSClient

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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