graphql

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2019 License: Apache-2.0 Imports: 9 Imported by: 2

README

graphql GoDoc Build Status Go Report Card

Low-level GraphQL client for Go.

  • Simple, familiar API
  • Respects context.Context timeouts and cancellation
  • Build and execute any kind of GraphQL request
  • Use strong Go types for response data
  • Use variables and upload files
  • Simple error handling

Installation

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

$ go get github.com/machinebox/graphql

Usage

import "context"

// create a client (safe to share across requests)
client := graphql.NewClient("https://machinebox.io/graphql")

// make a request
req := graphql.NewRequest(`
    query ($key: String!) {
        items (id:$key) {
            field1
            field2
            field3
        }
    }
`)

// set any variables
req.Var("key", "value")

// set header fields
req.Header.Set("Cache-Control", "no-cache")

// define a Context for the request
ctx := context.Background()

// run it and capture the response
var respData ResponseStruct
if err := client.Run(ctx, req, &respData); err != nil {
    log.Fatal(err)
}
File support via multipart form data

By default, the package will send a JSON body. To enable the sending of files, you can opt to use multipart form data instead using the UseMultipartForm option when you create your Client:

client := graphql.NewClient("https://machinebox.io/graphql", graphql.UseMultipartForm())

For more information, read the godoc package documentation or the blog post.

Thanks

Thanks to Chris Broadfoot for design help.

Documentation

Overview

Package graphql provides a low level GraphQL client.

// create a client (safe to share across requests)
client := graphql.NewClient("https://machinebox.io/graphql")

// make a request
req := graphql.NewRequest(`
    query ($key: String!) {
        items (id:$key) {
            field1
            field2
            field3
        }
    }
`)

// set any variables
req.Var("key", "value")

// run it and capture the response
var respData ResponseStruct
if err := client.Run(ctx, req, &respData); err != nil {
    log.Fatal(err)
}

Specify client

To specify your own http.Client, use the WithHTTPClient option:

httpclient := &http.Client{}
client := graphql.NewClient("https://machinebox.io/graphql", graphql.WithHTTPClient(httpclient))

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client added in v0.2.0

type Client struct {

	// Log is called with various debug information.
	// To log to standard out, use:
	//  client.Log = func(s string) { log.Println(s) }
	Log func(s string)
	// contains filtered or unexported fields
}

Client is a client for interacting with a GraphQL API.

func NewClient added in v0.2.0

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

NewClient makes a new Client capable of making GraphQL requests.

func (*Client) Run added in v0.2.0

func (c *Client) Run(ctx context.Context, req *Request, resp interface{}) error

Run executes the query and unmarshals the response from the data field into the response object. Pass in a nil response object to skip response parsing. If the request fails or the server returns an error, the returned error will be of type Errors. Type assert to get the underlying errors:

err := client.Run(..)
if err != nil {
  if gqlErrors, ok := err.(graphql.Errors); ok {
    for _, e := range gqlErrors {
      // Server returned an error
    }
  }
  // Another error occurred
}

type ClientOption added in v0.2.0

type ClientOption func(*Client)

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

func ImmediatelyCloseReqBody added in v0.2.3

func ImmediatelyCloseReqBody() ClientOption

ImmediatelyCloseReqBody will close the req body immediately after each request body is ready

func UseMultipartForm added in v0.2.2

func UseMultipartForm() ClientOption

UseMultipartForm uses multipart/form-data and activates support for files.

func WithHTTPClient added in v0.2.0

func WithHTTPClient(httpclient *http.Client) ClientOption

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

NewClient(endpoint, WithHTTPClient(specificHTTPClient))

type Error added in v0.2.3

type Error struct {
	// Message contains the error message.
	Message string
	// Locations contains the locations in the GraphQL document that caused the
	// error if the error can be associated to a particular point in the
	// requested GraphQL document.
	Locations []Location
	// Path contains the key path of the response field which experienced the
	// error. This allows clients to identify whether a nil result is
	// intentional or caused by a runtime error.
	Path []interface{}
	// Extensions may contain additional fields set by the GraphQL service,
	// such as	an error code.
	Extensions map[string]interface{}
}

An Error contains error information returned by the GraphQL server.

func (Error) Error added in v0.2.3

func (e Error) Error() string

type Errors added in v0.2.3

type Errors []Error

Errors contains all the errors that were returned by the GraphQL server.

func (Errors) Error added in v0.2.3

func (ee Errors) Error() string

type File added in v0.2.3

type File struct {
	Field string
	Name  string
	R     io.Reader
}

File represents a file to upload.

type Location added in v0.2.3

type Location struct {
	Line   int
	Column int
}

A Location is a location in the GraphQL query that resulted in an error. The location may be returned as part of an error response.

type Request

type Request struct {

	// Header represent any request headers that will be set
	// when the request is made.
	Header http.Header
	// contains filtered or unexported fields
}

Request is a GraphQL request.

func NewRequest

func NewRequest(q string) *Request

NewRequest makes a new Request with the specified string.

func (*Request) File

func (req *Request) File(fieldname, filename string, r io.Reader)

File sets a file to upload. Files are only supported with a Client that was created with the UseMultipartForm option.

func (*Request) Files added in v0.2.3

func (req *Request) Files() []File

Files gets the files in this request.

func (*Request) Query added in v0.2.3

func (req *Request) Query() string

Query gets the query string of this request.

func (*Request) Var

func (req *Request) Var(key string, value interface{})

Var sets a variable.

func (*Request) Vars added in v0.2.3

func (req *Request) Vars() map[string]interface{}

Vars gets the variables for this Request.

Jump to

Keyboard shortcuts

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