Add support for the query headers.

This commit is contained in:
2021-10-02 20:22:00 +01:00
parent 7ad04d7750
commit 333ec58bd2
7 changed files with 33 additions and 28 deletions
+4 -9
View File
@@ -8,7 +8,7 @@ Ps. It's Hasura friendly.
- [Reasoning](#reasoning) - [Reasoning](#reasoning)
- [Features](#features) - [Features](#features)
- [Usage example](#usage-example) - [Usage example](#usage-example)
- [Setting GraphQL endpoint](#setting-graphql-endpoint) - [Environment variables](#environment-variables)
- [Example reader code](#example-reader-code) - [Example reader code](#example-reader-code)
- [Working with results](#working-with-results) - [Working with results](#working-with-results)
@@ -27,15 +27,10 @@ Therefore, I present you the simple client to which you can copy & paste your gr
## Usage example ## Usage example
### Setting GraphQL endpoint ### Environment variables
You can set the endpoint variable within your code * `GRAPHQL_ENDPOINT` - Your GraphQL endpoint. Default: `http://127.0.0.1:9090/v1/graphql`
* `LOG_LEVEL` - Logging level. Default: `info`
```go
gql.GraphQLUrl = "http://127.0.0.1:9090/v1/graphql"
```
or as an environment variable `GRAPHQL_ENDPOINT=http://127.0.0.1:9090/v1/graphql`
### Example reader code ### Example reader code
+5 -4
View File
@@ -28,7 +28,7 @@ var (
json = jsoniter.ConfigCompatibleWithStandardLibrary json = jsoniter.ConfigCompatibleWithStandardLibrary
) )
type connHandler struct { type GraphQL struct {
Endpoint string Endpoint string
HttpClient *http.Client HttpClient *http.Client
Log *logging.LogConfig Log *logging.LogConfig
@@ -45,12 +45,13 @@ func pickGraphqlEndpoint() (graphqlEndpoint string) {
return graphqlEndpoint return graphqlEndpoint
} }
func NewConnection() *connHandler { func NewConnection() *GraphQL {
return &connHandler{ return &GraphQL{
Endpoint: pickGraphqlEndpoint(), Endpoint: pickGraphqlEndpoint(),
HttpClient: &http.Client{ HttpClient: &http.Client{
Transport: &http2.Transport{ Transport: &http2.Transport{
AllowHTTP: true, DisableCompression: true,
AllowHTTP: true,
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
return net.Dial(network, addr) return net.Dial(network, addr)
}, },
+3 -4
View File
@@ -33,26 +33,25 @@ func TestSuiteRun(t *testing.T) {
func (suite *TestSuite) TestNewConnection() { func (suite *TestSuite) TestNewConnection() {
type args struct { type args struct {
endpoint string endpoint string
debug bool
} }
tests := []struct { tests := []struct {
name string name string
args args args args
want *connHandler want *GraphQL
}{ }{
{ {
name: "New connection: Env variable endpoint", name: "New connection: Env variable endpoint",
args: args{ args: args{
endpoint: "http://localhost:8080/graphql", endpoint: "http://localhost:8080/graphql",
}, },
want: &connHandler{ want: &GraphQL{
Endpoint: "http://localhost:8080/graphql", Endpoint: "http://localhost:8080/graphql",
}, },
}, },
{ {
name: "New connection: No env variable endpoint", name: "New connection: No env variable endpoint",
args: args{}, args: args{},
want: &connHandler{ want: &GraphQL{
Endpoint: "http://127.0.0.1:9090/v1/graphql", Endpoint: "http://127.0.0.1:9090/v1/graphql",
}, },
}, },
+3 -2
View File
@@ -1,6 +1,7 @@
package logging package logging
import ( import (
"fmt"
stdlog "log" stdlog "log"
"os" "os"
"time" "time"
@@ -65,8 +66,8 @@ func log(contextLog *zerolog.Event, message string, v ...map[string]interface{})
if len(v) > 0 { if len(v) > 0 {
for _, m := range v { for _, m := range v {
for k, v := range m { for k, v := range m {
if !pandati.IsZero(v) { if !pandati.IsZero(v) && !pandati.IsZero(k) {
contextLog.Str(k, v.(string)) contextLog.Str(k, fmt.Sprintf("%v", v))
} }
} }
} }
+13 -4
View File
@@ -4,7 +4,9 @@ import (
"bytes" "bytes"
"errors" "errors"
"fmt" "fmt"
"io"
"io/ioutil" "io/ioutil"
"net/http"
"github.com/lukaszraczylo/pandati" "github.com/lukaszraczylo/pandati"
) )
@@ -21,7 +23,7 @@ type queryResults struct {
} `json:"errors"` } `json:"errors"`
} }
func (g *connHandler) queryBuilder(queryContent string, queryVariables interface{}) ([]byte, error) { func (g *GraphQL) queryBuilder(queryContent string, queryVariables interface{}) ([]byte, error) {
var qb = &requestBase{ var qb = &requestBase{
Query: queryContent, Query: queryContent,
Variables: queryVariables, Variables: queryVariables,
@@ -40,18 +42,25 @@ func (g *connHandler) queryBuilder(queryContent string, queryVariables interface
return j2, err return j2, err
} }
func (g *connHandler) Query(queryContent string, queryVariables interface{}) (responseContent string, err error) { func (g *GraphQL) Query(queryContent string, queryVariables interface{}, queryHeaders map[string]interface{}) (responseContent string, err error) {
g.Log.Debug("Query details", map[string]interface{}{"_query": queryContent, "_variables": queryVariables}) g.Log.Debug("Query details", map[string]interface{}{"_query": queryContent, "_variables": queryVariables})
query, err := g.queryBuilder(queryContent, queryVariables) query, err := g.queryBuilder(queryContent, queryVariables)
if err != nil { if err != nil {
g.Log.Error("Unable to build the query", map[string]interface{}{"_error": err.Error()}) g.Log.Error("Unable to build the query", map[string]interface{}{"_error": err.Error()})
return "", err return "", err
} }
httpResponse, err := g.HttpClient.Post(g.Endpoint, "application/json", bytes.NewBuffer(query)) httpRequest, err := http.NewRequest("POST", g.Endpoint, bytes.NewBuffer(query))
httpRequest.Header.Add("Content-Type", "application/json")
for header, value := range queryHeaders {
httpRequest.Header.Add(fmt.Sprintf("%v", header), fmt.Sprintf("%v", value))
}
httpResponse, err := g.HttpClient.Do(httpRequest)
if err != nil { if err != nil {
g.Log.Error("Unable to send the query", map[string]interface{}{"_error": err.Error()}) g.Log.Error("Unable to send the query", map[string]interface{}{"_error": err.Error()})
return "", err return "", err
} }
defer io.Copy(ioutil.Discard, httpResponse.Body)
defer httpResponse.Body.Close() defer httpResponse.Body.Close()
body, err := ioutil.ReadAll(httpResponse.Body) body, err := ioutil.ReadAll(httpResponse.Body)
@@ -68,7 +77,7 @@ func (g *connHandler) Query(queryContent string, queryVariables interface{}) (re
if !pandati.IsZero(queryResult.Errors) { if !pandati.IsZero(queryResult.Errors) {
g.Log.Error("Query returned error", map[string]interface{}{"_query": queryContent, "_variables": queryVariables, "_error": fmt.Sprintf("%v", queryResult.Errors)}) g.Log.Error("Query returned error", map[string]interface{}{"_query": queryContent, "_variables": queryVariables, "_error": fmt.Sprintf("%v", queryResult.Errors)})
return "", errors.New(fmt.Sprintf("%v", queryResult.Errors[0].Message)) return "", fmt.Errorf("%v", queryResult.Errors[0].Message)
} }
if pandati.IsZero(queryResult.Data) { if pandati.IsZero(queryResult.Data) {
+2 -2
View File
@@ -4,7 +4,7 @@ import (
"testing" "testing"
) )
func Benchmark_connHandler_Query(t *testing.B) { func Benchmark_GraphQL_Query(t *testing.B) {
type args struct { type args struct {
queryContent string queryContent string
queryVariables interface{} queryVariables interface{}
@@ -58,7 +58,7 @@ func Benchmark_connHandler_Query(t *testing.B) {
server, serverURL := mockGraphQLServerResponses(tt.mockedReply) server, serverURL := mockGraphQLServerResponses(tt.mockedReply)
g.Endpoint = serverURL g.Endpoint = serverURL
for n := 0; n < t.N; n++ { for n := 0; n < t.N; n++ {
g.Query(tt.args.queryContent, tt.args.queryVariables) g.Query(tt.args.queryContent, tt.args.queryVariables, nil)
} }
server.Close() server.Close()
}) })
+3 -3
View File
@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func (suite *TestSuite) Test_connHandler_queryBuilder() { func (suite *TestSuite) Test_GraphQL_queryBuilder() {
type args struct { type args struct {
queryContent string queryContent string
queryVariables interface{} queryVariables interface{}
@@ -49,7 +49,7 @@ func (suite *TestSuite) Test_connHandler_queryBuilder() {
} }
} }
func (suite *TestSuite) Test_connHandler_Query() { func (suite *TestSuite) Test_GraphQL_Query() {
type args struct { type args struct {
queryContent string queryContent string
queryVariables interface{} queryVariables interface{}
@@ -99,7 +99,7 @@ func (suite *TestSuite) Test_connHandler_Query() {
os.Setenv("GRAPHQL_ENDPOINT", tt.endpoint) os.Setenv("GRAPHQL_ENDPOINT", tt.endpoint)
} }
g := NewConnection() g := NewConnection()
gotResult, gotErr := g.Query(tt.args.queryContent, tt.args.queryVariables) gotResult, gotErr := g.Query(tt.args.queryContent, tt.args.queryVariables, nil)
if tt.wantErr { if tt.wantErr {
assert.Error(t, gotErr) assert.Error(t, gotErr)
} }