gqlclient

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 4, 2021 License: MIT Imports: 10 Imported by: 0

README

gqlclient GoDoc

GraphQL client for Go.

  • Simple, familiar API
  • Pass context.Context to the http client
  • Build and execute a GraphQL request using json or multipart
  • Use strong Go types for response data
  • Use variables, custom headers and a custom http client
  • Advanced error handling

Installation

Make sure you have a working Go environment. To install gqlclient, simply run:

$ go get github.com/weavedev/go-gqlclient

Usage

import (
    gql "github.com/weavedev/go-gqlclient"
)


// Create a client (safe to share across requests)
client := gql.NewClient(
    "https://localhost/graphql",
    // Optionally supply options:
    // Set default headers.
    gql.WithDefaultHeader("Authorization", "Bearer " + token),
    // Use a custom http.Client.
    gql.WithHTTPClient(customClient),
    // Use another request builder (default: gql.JSONRequestBuilder).
    gql.WithRequestBuilder(gql.MultipartRequestBuilder),
)

// Make a request
req := gql.NewRequest(`
    query ($key: String!) {
        item(id: $key) {
            field1
            field2
            field3
        }
    }`,
    // Optionally supply options:
    // Set any variables.
    gql.WithVar("key", "value"),
    // Set header fields.
    gql.WithHeader("Cache-Control", "no-cache"),
    // Pass a Context for the request (default: context.Background()).
    gql.WithContext(ctx),
)

// Do the request and capture the response.
var resp struct {
    Item struct {
        Field1 string
        Field2 string
        Field3 string
    }
}
err := client.Do(req, &resp)

// Inspect the returned GraphQL errors
var gqlerrs gql.ErrorList
if errors.As(err, &gqlerrs) {
    // Check path
    println(gqlerrs[0].Path)
}

Thanks

Inspired by https://github.com/machinebox/graphql

Documentation

Overview

Package gqlclient provides a client for interacting with a GraphQL endpoint.

Create a client (safe to share across requests)

client := gqlclient.NewClient(
    "https://localhost/graphql",
    // Optionally supply options:
    // Set default headers.
    gqlclient.WithDefaultHeader("Authorization", "Bearer " + token),
    // Use a custom http.Client.
    gqlclient.WithHTTPClient(customClient),
    // Use another request builder (default: gqlclient.JSONRequestBuilder).
    gqlclient.WithRequestBuilder(gqlclient.MultipartRequestBuilder),
)

Make a request

req := gqlclient.NewRequest(`
    query ($key: String!) {
        item(id: $key) {
            field1
            field2
            field3
        }
    }`,
    // Optionally supply options:
    // Set any variables.
    gqlclient.WithVar("key", "value"),
    // Set header fields.
    gqlclient.WithHeader("Cache-Control", "no-cache"),
    // Pass a Context for the request (default: context.Background()).
    gqlclient.WithContext(ctx),
)

Do the request and capture the response.

var resp struct {
    Item struct {
        Field1 string
        Field2 string
        Field3 string
    }
}
err := client.Do(req, &resp)

Inspect the returned GraphQL errors

var gqlerrs gqlclient.ErrorList
if errors.As(err, &gqlerrs) {
    // Check path
    println(gqlerrs[0].Path)
}

Index

Constants

This section is empty.

Variables

View Source
var ErrBadResponse = errors.New("response was not GraphQL compliant")

ErrBadResponse is used when the response body cannot be parsed.

Functions

func JSONRequestBuilder

func JSONRequestBuilder(endpoint string, req *Request) (*http.Request, error)

JSONRequestBuilder creates an http.Request based on a GraphQL Request using a json encoding.

func MultipartRequestBuilder

func MultipartRequestBuilder(endpoint string, req *Request) (*http.Request, error)

MultipartRequestBuilder creates an http.Request based on a GraphQL Request using multipart encoding.

Types

type Client

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

Client is a client for interacting with a GraphQL API.

func NewClient

func NewClient(endpoint string, opts ...ClientOption) *Client

NewClient makes a new Client capable of making GraphQL requests.

func (*Client) Do

func (c *Client) Do(req *Request, resp interface{}) (err error)

Do executes the Request and decodes the response from the data field into the given response object. Pass in a nil response object to skip response parsing. If the request fails or the server returns an error, the first error will be returned.

type ClientOption

type ClientOption func(*Client)

ClientOption are functions that are passed into NewClient to modify the behaviour of the Client.

func WithDefaultHeader

func WithDefaultHeader(key string, value string) ClientOption

WithDefaultHeader sets a default value for a header entry of every Request sent with this client.

NewClient(endpoint, WithDefaultHeader(key, value))

func WithHTTPClient

func WithHTTPClient(httpclient HTTPClient) ClientOption

WithHTTPClient specifies the underlying http.Client to use when making requests.

NewClient(endpoint, WithHTTPClient(specificHTTPClient))

func WithRequestBuilder

func WithRequestBuilder(builder RequestBuilder) ClientOption

WithRequestBuilder sets a function that executes the Request sent with this client.

NewClient(endpoint, WithDefaultHeader(key, value))

type Error

type Error struct {
	Message    string                 `json:"message"`
	Path       ast.Path               `json:"path,omitempty"`
	Locations  []gqlerror.Location    `json:"locations,omitempty"`
	Extensions map[string]interface{} `json:"extensions,omitempty"`
}

Error contains all the data that a GraphQL error can contain.

func (Error) Error

func (e Error) Error() string

Error formats the error using locations, path and message.

type ErrorList

type ErrorList []*Error

ErrorList is an error type to embed the errors list from a GraphQL response.

func (ErrorList) Error

func (m ErrorList) Error() string

Error returns the first error from a GraphQL response.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

type HTTPError

type HTTPError struct {
	StatusCode int
}

HTTPError represents an error that occurred in the http transport layer and not in the GraphQL layer.

func NewHTTPError

func NewHTTPError(statusCode int) *HTTPError

NewHTTPError creates a new HTTPError with the given http status code.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type Request

type Request struct {
	Query     string                 `json:"query"`
	Variables map[string]interface{} `json:"variables,omitempty"`
	// contains filtered or unexported fields
}

Request is a GraphQL request.

func NewRequest

func NewRequest(query string, opts ...RequestOption) *Request

NewRequest makes a new Request with the specified string.

type RequestBuilder

type RequestBuilder func(endpoint string, req *Request) (*http.Request, error)

type RequestOption

type RequestOption func(*Request)

RequestOption are functions that are passed into NewRequest to modify the Request.

func WithContext

func WithContext(ctx context.Context) RequestOption

WithContext sets the Context which is used when executing the Request.

NewRequest(query, WithContext(ctx))

func WithHeader

func WithHeader(key string, value string) RequestOption

WithHeader sets an entry in the header of a Request to the specified value.

NewRequest(query, WithHeader(key, value))

func WithVar

func WithVar(name string, value interface{}) RequestOption

WithVar defines the value of a variable in the query of a Request.

NewRequest(query, WithVar(name, value))

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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