grafik

module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2022 License: MIT

README

grafik

Build Status CodeQL Go Report Card codecov Latest Tag Go Reference GitHub PRs Welcome

grafik logo

grafik [/ˈɡra.fik/] (Origin: Polish): illustrator, graphic designer

Grafik is a schema based GraphQL Go code generator & HTTP client.

Foreword

Grafik is still in early stage and under active development. If you notice a bug, or you would like to request a new feature, please raise an issue/PR.

Introduction

Writing type-safe GraphQL code in Go is difficult. Developers usually end up manually writing queries as a string and passing it inside the JSON field. This is not only inefficient and error-prone, but also an unpleasant development experience as we cannot use auto-completion, formatting and schema validation features.

Grafik allows you to write your GraphQL queries and mutations in .graphql file. It will not only generate Go code like structs, functions and interfaces, but also provide convenient Execute function to execute your GraphQL code instantly.

Due to its nature, it is also extremely easy to mock.

Installation

Assuming you have Go installed on your machine, first install grafikgen.

Note: Make sure to add $GOPATH/bin to your PATH.

Go version < 1.16
GO111MODULE=on go install github.com/Bartosz-D3V/grafik/grafikgen@latest
Go 1.16+
go install github.com/Bartosz-D3V/grafik/grafikgen@latest

To add grafik GraphQL client add grafik as a dependency to your project:

go get github.com/Bartosz-D3V/grafik

Running grafikgen

Grafik requires two types of GraphQL files - schema.graphql that represents the schema of the GraphQL endpoint and query.graphql that holds all the queries and mutations.

Grafik will parse GraphQL files, create AST using gqlparser and then generate GraphQL Go client that can be used programmatically.

Example

schema.graphql

type Query {
    countResults(condition: Condition!): Result
}

input Condition {
    idSet: [ID]!
}

type Result {
    total: Int
}

query.graphql

query countResults($condition: Condition!){
    countResults(condition: $condition) {
        total
    }
}

Command to generate GraphQL client

grafikgen
    --schema_source=./graphql/schema.graphql \
    --query_source=./graphql/query.graphql \
    --package_name=main \
    --client_name=GraphqlClient \
    --destination=./graphql/graphql_client.go

Generated code:

// Generated with grafik. DO NOT EDIT

package main

import (
	"context"
	GraphqlClient "github.com/Bartosz-D3V/grafik/client"
	"net/http"
)

type Condition struct {
	IdSet []string `json:"idSet"`
}

type Result struct {
	Total int `json:"total"`
}

const countResults = `query countResults($condition: Condition!){
    countResults(condition: $condition) {
        total
    }
}`

type GraphqlClient interface {
	CountResults(condition Condition, header http.Header) (*http.Response, error)
}

func (c *graphqlClient) CountResults(ctx context.Context, condition Condition, header http.Header) (*http.Response, error) {
	params := make(map[string]interface{}, 1)
	params["condition"] = condition

	return c.ctrl.Execute(ctx, countResults, params, header)
}

type CountResultsResponse struct {
	Data   CountResultsData `json:"data"`
	Errors []GraphQLError   `json:"errors"`
}

type CountResultsData struct {
	CountResults Result `json:"countResults"`
}

type GraphQLError struct {
	Message    string                 `json:"message"`
	Locations  []GraphQLErrorLocation `json:"locations"`
	Extensions GraphQLErrorExtensions `json:"extensions"`
}

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

type GraphQLErrorExtensions struct {
	Code string `json:"code"`
}

type graphqlClient struct {
	ctrl GraphqlClient.Client
}

func New(endpoint string, client *http.Client) GraphqlClient {
	return &graphqlClient{
		ctrl: GraphqlClient.New(endpoint, client),
	}
}

Use the New function from generated code to create instance of your GraphQL client by providing endpoint and HTTP client.

Grafik generates the GraphQL types used by operations defined in query.graphql file.

Function with receiver returns *http.Response - use json.Unmarshall to convert the response to the actual Go struct defined in generated grafik client.

By default, the GraphQL operation's return type is named using the following pattern: graphqlOperationResponse (i.e. CountResultsResponse).

See more examples and how to use the client programmatically.

Authorization

Grafik does not provide any direct authorization mechanism because it accepts http.Client.

For example - http.Client can be configured with CookieJar to provide appropriate cookies.

If GraphQL endpoint requires JWT inside an HTTP header, it can be passed as a http.Header argument or http.RoundTripper.

Flags

The graffikgen tool is used to generate GraphQL clients in Go. It supports the following flags:

  • -schema_source: [required] Location of the GraphQL schema file. Either absolute or relative.
  • -query_source: [required] Location of the GraphQL query file. Either absolute or relative.
  • -package_name: [optional] Name of the generated Go GraphQL client package; defaults to the name of the GraphQL query file with 'grafik_' prefix.
  • -client_name: [optional] Name of the generated Go GraphQL client; defaults to the name of the GraphQL query file with 'Grafik' prefix and 'Client' postfix.
  • -destination: [optional] Output filename with path. Either absolute or relative; defaults to the current directory and client name.
  • -use_pointers: [optional] [optional] Generate public GraphQL structs' fields as pointers; defaults to false.

Help

To view the help run grafikgen help command.

Directories

Path Synopsis
Package client contains the code used internally by grafik to prepare & send HTTP requests.
Package client contains the code used internally by grafik to prepare & send HTTP requests.
Package common contains commonly used helper functions used within grafik project.
Package common contains commonly used helper functions used within grafik project.
Package ds (Data Structure) contains all golang data structures used by generator.
Package ds (Data Structure) contains all golang data structures used by generator.
Package evaluator contains the logic responsible for evaluating schema & query GraphQL Abstract Syntax Tree [AST].
Package evaluator contains the logic responsible for evaluating schema & query GraphQL Abstract Syntax Tree [AST].
examples
Package generator abstracts writing specific Go constructs (interfaces, structs etc) into IO.
Package generator abstracts writing specific Go constructs (interfaces, structs etc) into IO.
Package main provides grafikgen CLI tools used for generating grafik clients.
Package main provides grafikgen CLI tools used for generating grafik clients.
Package test contains GraphQL code (Schemas & Queries) used for unit tests.
Package test contains GraphQL code (Schemas & Queries) used for unit tests.
Package visitor abstracts logic responsible for determining which custom types from GraphQL Schema file should be generated based on usage in GraphQL query file.
Package visitor abstracts logic responsible for determining which custom types from GraphQL Schema file should be generated based on usage in GraphQL query file.

Jump to

Keyboard shortcuts

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