Compare commits

...
22 Commits
Author SHA1 Message Date
lukaszraczyloandgithub-actions[bot] 63e449ef77 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-01-07 03:09:25 +00:00
lukaszraczyloandgithub-actions[bot] 50cfc5f98d Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-01-05 03:10:35 +00:00
lukaszraczyloandgithub-actions[bot] 4a575ac9c8 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-12-19 03:12:34 +00:00
lukaszraczyloandgithub-actions[bot] f54cedaeb3 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-12-12 03:17:28 +00:00
lukaszraczyloandgithub-actions[bot] 1080083384 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-12-10 03:18:24 +00:00
lukaszraczyloandgithub-actions[bot] 941aadb869 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-12-05 03:17:28 +00:00
lukaszraczyloandgithub-actions[bot] 8174ae6f9c Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-11-09 03:06:06 +00:00
lukaszraczyloandgithub-actions[bot] 992a29da85 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-11-08 03:06:12 +00:00
lukaszraczyloandgithub-actions[bot] ecf2c06401 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-10-05 03:07:15 +00:00
lukaszraczyloandgithub-actions[bot] fb0785229c Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-10-03 03:08:02 +00:00
lukaszraczylo 8ac446db41 fixup! Move towards go-reflect from goccy. 2024-09-28 17:01:17 +01:00
lukaszraczylo 586af64d70 Move towards go-reflect from goccy. 2024-09-28 17:00:53 +01:00
lukaszraczylo 50c1033ad1 Use the mocks for tests and benchmarks. 2024-09-13 21:27:34 +01:00
lukaszraczylo 7a791965ca Improve the speed & reliability of the code. 2024-09-13 21:27:34 +01:00
lukaszraczyloandgithub-actions[bot] 05b057c67c Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-09-06 03:04:47 +00:00
lukaszraczyloandgithub-actions[bot] 9c729d814a Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-09-05 03:03:42 +00:00
lukaszraczyloandgithub-actions[bot] 9d5e2122b8 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-08-09 03:03:59 +00:00
lukaszraczyloandgithub-actions[bot] a19f1d257a Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-08-07 03:03:51 +00:00
lukaszraczyloandgithub-actions[bot] 563c952c78 Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-08-05 03:03:39 +00:00
lukaszraczyloandgithub-actions[bot] 2f259a4b3f Update go.mod and go.sum
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-07-31 15:18:46 +00:00
lukaszraczyloandGitHub 957857537a Update autoupdate.yaml 2024-07-31 16:16:59 +01:00
lukaszraczylo 4ea4bbb6cc Add autoupdate functionality. 2024-07-23 20:25:22 +01:00
13 changed files with 199 additions and 270 deletions
+3 -2
View File
@@ -3,7 +3,7 @@ name: Autoupdate go.mod and go.sum
on:
workflow_dispatch:
schedule:
- cron: "30 2 * * *"
- cron: "0 3 * * *"
env:
GO_VERSION: ">=1.21"
@@ -63,7 +63,8 @@ jobs:
- name: Run unit tests
run: |
CI_RUN=${CI} make test
git config --global --add safe.directory /__w/go-simple-graphql
git config --global --add safe.directory /__w/go-simple-graphql/go-simple-graphql
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v5
with:
+23 -45
View File
@@ -27,16 +27,9 @@ func (qe *QueryExecutor) executeQuery() ([]byte, error) {
defer bufferPool.Put(buf)
buf.Reset()
_, err := buf.Write(qe.Query)
if err != nil {
qe.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't write to buffer",
Pairs: map[string]interface{}{"error": err.Error()},
})
return nil, err
}
buf.Write(qe.Query)
httpRequest, err := http.NewRequest(http.MethodPost, qe.endpoint, buf)
httpRequest, err := http.NewRequest(http.MethodPost, qe.endpoint, nil)
if err != nil {
qe.Logger.Error(&libpack_logger.LogMessage{
Message: "Can't create HTTP request",
@@ -48,78 +41,62 @@ func (qe *QueryExecutor) executeQuery() ([]byte, error) {
for key, value := range qe.Headers {
httpRequest.Header.Set(key, fmt.Sprint(value))
}
// Set Content-Type header if not already set
if httpRequest.Header.Get("Content-Type") == "" {
httpRequest.Header.Set("Content-Type", "application/json")
}
retriesMax := 1
if qe.Retries {
qe.Logger.Debug(&libpack_logger.LogMessage{
Message: "Retries enabled",
Pairs: map[string]interface{}{"retries": qe.retries_number},
})
retriesMax = qe.retries_number
} else {
qe.Logger.Debug(&libpack_logger.LogMessage{
Message: "Retries disabled",
Pairs: map[string]interface{}{"retries": 1},
})
}
var queryResult queryResults
err = retry.Do(
func() error {
// Reset buffer before each retry
buf.Reset()
buf.Write(qe.Query)
// Set the body of the request
httpRequest.Body = io.NopCloser(bytes.NewReader(buf.Bytes()))
httpRequest.ContentLength = int64(buf.Len())
httpResponse, err := qe.client.Do(httpRequest)
if err != nil {
qe.Logger.Debug(&libpack_logger.LogMessage{
Message: "Error executing HTTP request",
Pairs: map[string]interface{}{"error": err.Error()},
})
return err
}
defer func() {
_, err := io.Copy(io.Discard, httpResponse.Body)
if err != nil {
qe.Logger.Debug(&libpack_logger.LogMessage{
Message: "Error discarding HTTP response body",
Pairs: map[string]interface{}{"error": err.Error()},
})
}
io.Copy(io.Discard, httpResponse.Body)
httpResponse.Body.Close()
}()
if httpResponse.StatusCode < http.StatusOK || httpResponse.StatusCode >= http.StatusNoContent {
if httpResponse.StatusCode < http.StatusOK || httpResponse.StatusCode >= http.StatusMultipleChoices {
return fmt.Errorf("HTTP error - status code: %s for %s", httpResponse.Status, httpRequest.URL)
}
var reader io.ReadCloser
var reader io.Reader
encoding := httpResponse.Header.Get("Content-Encoding")
if encoding == "gzip" {
reader, err = gzip.NewReader(httpResponse.Body)
gzipReader, err := gzip.NewReader(httpResponse.Body)
if err != nil {
qe.Logger.Debug(&libpack_logger.LogMessage{
Message: "Error creating gzip reader",
Pairs: map[string]interface{}{"error": err.Error()},
})
return fmt.Errorf("error creating gzip reader: %w", err)
}
defer reader.Close()
defer gzipReader.Close()
reader = gzipReader
} else {
reader = httpResponse.Body
}
// Read all response body
body, err := io.ReadAll(reader)
if err != nil {
qe.Logger.Debug(&libpack_logger.LogMessage{
Message: "Error reading HTTP response",
Pairs: map[string]interface{}{"error": err.Error()},
})
return fmt.Errorf("error reading HTTP response: %w", err)
}
// Unmarshal response
err = json.Unmarshal(body, &queryResult)
if err != nil {
qe.Logger.Debug(&libpack_logger.LogMessage{
Message: "Error unmarshalling HTTP response",
Pairs: map[string]interface{}{"error": err.Error()},
})
return fmt.Errorf("error unmarshalling HTTP response: %w", err)
}
@@ -160,6 +137,7 @@ func (qe *QueryExecutor) executeQuery() ([]byte, error) {
return nil, errors.New("error executing query: no data")
}
// Marshal queryResult.Data
jsonData, err := json.Marshal(queryResult.Data)
if err != nil {
qe.Logger.Debug(&libpack_logger.LogMessage{
+8 -10
View File
@@ -4,23 +4,21 @@ go 1.21
require (
github.com/avast/retry-go/v4 v4.6.0
github.com/goccy/go-json v0.10.2
github.com/gookit/goutil v0.6.15
github.com/rs/zerolog v1.32.0
github.com/goccy/go-json v0.10.4
github.com/goccy/go-reflect v1.2.0
github.com/gookit/goutil v0.6.18
github.com/stretchr/testify v1.9.0
golang.org/x/net v0.25.0
golang.org/x/net v0.34.0
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gookit/color v1.5.4 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/term v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
golang.org/x/sync v0.10.0 // indirect
golang.org/x/sys v0.29.0 // indirect
golang.org/x/term v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+16 -29
View File
@@ -1,46 +1,33 @@
github.com/avast/retry-go/v4 v4.6.0 h1:K9xNA+KeB8HHc2aWFuLb25Offp+0iVRXEvFx8IinRJA=
github.com/avast/retry-go/v4 v4.6.0/go.mod h1:gvWlPhBVsvBbLkVGDg/KwvBv0bEkCOLRRSHKIr2PyOE=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/goccy/go-json v0.10.4 h1:JSwxQzIqKfmFX1swYPpUThQZp/Ka4wzJdK0LWVytLPM=
github.com/goccy/go-json v0.10.4/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-reflect v1.2.0 h1:O0T8rZCuNmGXewnATuKYnkL0xm6o8UNOJZd/gOkb9ms=
github.com/goccy/go-reflect v1.2.0/go.mod h1:n0oYZn8VcV2CkWTxi8B9QjkCoq6GTtCEdfmR66YhFtE=
github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w=
github.com/gookit/goutil v0.6.15 h1:mMQ0ElojNZoyPD0eVROk5QXJPh2uKR4g06slgPDF5Jo=
github.com/gookit/goutil v0.6.15/go.mod h1:qdKdYEHQdEtyH+4fNdQNZfJHhI0jUZzHxQVAV3DaMDY=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/gookit/goutil v0.6.18 h1:MUVj0G16flubWT8zYVicIuisUiHdgirPAkmnfD2kKgw=
github.com/gookit/goutil v0.6.18/go.mod h1:AY/5sAwKe7Xck+mEbuxj0n/bc3qwrGNe3Oeulln7zBA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0=
github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.20.0 h1:VnkxpohqXaOBYJtBmEppKUG6mXpi+4O6purfc2+sMhw=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg=
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+2 -2
View File
@@ -9,7 +9,7 @@ import (
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
)
func searchForKeysInMapStringInterface(msi map[string]interface{}, key string) (value any) {
func searchForKeysInMapStringInterface(msi map[string]interface{}, key string) interface{} {
if msi == nil {
return nil
}
@@ -17,7 +17,7 @@ func searchForKeysInMapStringInterface(msi map[string]interface{}, key string) (
}
func calculateHash(query *Query) string {
hash := md5.Sum([]byte(query.JsonQuery))
hash := md5.Sum(query.JsonQuery)
return hex.EncodeToString(hash[:])
}
+2 -1
View File
@@ -1,8 +1,9 @@
package gql
import (
"reflect"
"testing"
"github.com/goccy/go-reflect"
)
func (suite *Tests) Test_searchForKeysInMapStringInterface() {
+1 -1
View File
@@ -4,11 +4,11 @@ import (
"bytes"
"fmt"
"os"
"reflect"
"testing"
"time"
"github.com/goccy/go-json"
"github.com/goccy/go-reflect"
)
func captureStderr(f func()) string {
+5
View File
@@ -1,6 +1,7 @@
package gql
import (
"net/http"
"time"
"github.com/gookit/goutil/envutil"
@@ -38,3 +39,7 @@ func (b *BaseClient) SetOutput(responseType string) {
// TODO: implement
b.responseType = responseType
}
func (b *BaseClient) SetHTTPClient(client *http.Client) {
b.client = client
}
+67
View File
@@ -0,0 +1,67 @@
// mock_server.go
package gql
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"golang.org/x/net/http2"
)
func StartMockServer() *httptest.Server {
// Create your handler
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Your existing handler code
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
var req struct {
Variables map[string]interface{} `json:"variables"`
Query string `json:"query"`
}
err = json.Unmarshal(bodyBytes, &req)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// Simple validation to check for unbalanced braces as a syntax error
if !strings.HasPrefix(strings.TrimSpace(req.Query), "query") || !strings.HasSuffix(strings.TrimSpace(req.Query), "}") {
resp := []byte(`{"errors":[{"message":"Syntax Error: Invalid query"}]}`)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
w.Write(resp)
return
}
var resp []byte
if strings.Contains(req.Query, "viewer") {
resp = []byte(`{"data":{"viewer":{"login":"mockuser"}}}`)
} else if strings.Contains(req.Query, "dragons") {
resp = []byte(`{"data":{"dragons":[{"name":"Mock Dragon 1"},{"name":"Mock Dragon 2"}]}}`)
} else {
resp = []byte(`{"errors":[{"message":"Unknown query"}]}`)
w.WriteHeader(http.StatusBadRequest)
}
w.Header().Set("Content-Type", "application/json")
w.Write(resp)
})
// Create an unstarted server
server := httptest.NewUnstartedServer(handler)
// Configure the server to support HTTP/2
http2.ConfigureServer(server.Config, &http2.Server{})
server.TLS = server.Config.TLSConfig
// Start the server with TLS
server.StartTLS()
return server
}
+16 -21
View File
@@ -1,8 +1,8 @@
package gql
import (
"bytes"
"fmt"
"sync"
"github.com/goccy/go-json"
"github.com/gookit/goutil"
@@ -10,17 +10,13 @@ import (
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
)
var jsonBufferPool = sync.Pool{
New: func() interface{} {
return new([]byte)
},
}
func (b *BaseClient) convertToJSON(v any) []byte {
jsonBuffer := jsonBufferPool.Get().(*[]byte)
defer jsonBufferPool.Put(jsonBuffer)
// Reuse buffer to reduce allocations
buf := bufferPool.Get().(*bytes.Buffer)
defer bufferPool.Put(buf)
buf.Reset()
*jsonBuffer = (*jsonBuffer)[:0]
// Use json.Marshal to avoid adding extra newline
jsonData, err := json.Marshal(v)
if err != nil {
b.Logger.Error(&libpack_logger.LogMessage{
@@ -29,8 +25,14 @@ func (b *BaseClient) convertToJSON(v any) []byte {
})
return nil
}
*jsonBuffer = append(*jsonBuffer, jsonData...)
return *jsonBuffer
// Copy the bytes to the buffer
buf.Write(jsonData)
// Copy the bytes to a new slice before returning
result := make([]byte, buf.Len())
copy(result, buf.Bytes())
return result
}
func (b *BaseClient) compileQuery(queryPartials ...any) *Query {
@@ -92,7 +94,7 @@ func (b *BaseClient) Query(query string, variables map[string]interface{}, heade
Message: "Cache hit",
Pairs: map[string]interface{}{"query": compiledQuery},
})
return cachedValue, nil
return b.decodeResponse(cachedValue)
}
b.Logger.Debug(&libpack_logger.LogMessage{
Message: "Cache miss",
@@ -100,13 +102,6 @@ func (b *BaseClient) Query(query string, variables map[string]interface{}, heade
})
}
if enableRetries || b.retries_enable {
b.Logger.Debug(&libpack_logger.LogMessage{
Message: "Retries enabled",
Pairs: nil,
})
}
q := &QueryExecutor{
BaseClient: b,
Query: compiledQuery.JsonQuery,
@@ -129,7 +124,7 @@ func (b *BaseClient) Query(query string, variables map[string]interface{}, heade
return nil, err
}
return q.decodeResponse(rv)
return b.decodeResponse(rv)
}
func (q *Query) parseHeadersAndVariables(headers map[string]interface{}) (enableCache, enableRetries, recompileRequired bool) {
+19 -2
View File
@@ -36,10 +36,15 @@ func Benchmark_convertToJson(bn *testing.B) {
b.convertToJSON(query)
}
}
func Benchmark_Query(bn *testing.B) {
mockServer := StartMockServer()
bn.Cleanup(func() {
mockServer.Close()
})
b := NewConnection()
query := `query { viewer { login } }`
b.SetEndpoint(mockServer.URL)
query := "query { viewer { login } }"
variables := map[string]interface{}{
"var1": "value1",
}
@@ -54,7 +59,13 @@ func Benchmark_Query(bn *testing.B) {
}
func Benchmark_QueryNoCacheNoRetry(bn *testing.B) {
mockServer := StartMockServer()
bn.Cleanup(func() {
mockServer.Close()
})
b := NewConnection()
b.SetEndpoint(mockServer.URL)
query := `query { viewer { login } }`
variables := map[string]interface{}{
"var1": "value1",
@@ -69,7 +80,13 @@ func Benchmark_QueryNoCacheNoRetry(bn *testing.B) {
}
func Benchmark_QueryWithEmptyVariables(bn *testing.B) {
mockServer := StartMockServer()
bn.Cleanup(func() {
mockServer.Close()
})
b := NewConnection()
b.SetEndpoint(mockServer.URL)
query := `query { viewer { login } }`
headers := map[string]interface{}{
"Authorization": "Bearer token",
+22 -156
View File
@@ -1,8 +1,9 @@
package gql
import (
"reflect"
"testing"
"github.com/goccy/go-reflect"
)
func (suite *Tests) TestBaseClient_convertToJSON() {
@@ -115,182 +116,48 @@ func (suite *Tests) TestBaseClient_Query() {
args args
wantReturned_value any
name string
graphQLServer string
wantType string
wantErr bool
}{
{
name: "TestBaseClient_Query_spacex_working",
graphQLServer: "https://spacex-production.up.railway.app/",
name: "TestBaseClient_Query_viewer",
args: args{
query: `query Dragons {
dragons {
name
}
}`,
query: "query { viewer { login } }",
variables: nil,
headers: map[string]interface{}{
"x-apollo-operation-name": "Dragons/github.com/lukaszraczylo/go-simple-graphql",
"x-apollo-operation-name": "ViewerQuery",
"content-type": "application/json",
},
},
wantReturned_value: string(`{"dragons":[{"name":"Dragon 1"},{"name":"Dragon 2"}]}`),
wantReturned_value: `{"viewer":{"login":"mockuser"}}`, // Adjusted expected value
wantErr: false,
},
{
name: "TestBaseClient_Query_spacex_invalid_query",
graphQLServer: "https://spacex-production.up.railway.app/",
name: "TestBaseClient_Query_dragons",
args: args{
query: `query Dragons {
dragons {
name
}
`,
dragons {
name
}
}`,
variables: nil,
headers: map[string]interface{}{
"x-apollo-operation-name": "Dragons/github.com/lukaszraczylo/go-simple-graphql",
"x-apollo-operation-name": "DragonsQuery",
"content-type": "application/json",
},
},
wantReturned_value: nil,
wantErr: true,
},
{
name: "TestBaseClient_Query_tgbotapp_working",
graphQLServer: "https://telegram-bot.app/v1/graphql",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
},
wantReturned_value: string(`{"__type":null}`),
wantReturned_value: `{"dragons":[{"name":"Mock Dragon 1"},{"name":"Mock Dragon 2"}]}`, // Adjusted expected value
wantErr: false,
},
{
name: "TestBaseClient_Query_tgbotapp_invalid_query",
graphQLServer: "https://telegram-bot.app/v1/graphql",
name: "TestBaseClient_Query_invalid_query",
args: args{
query: `query {
__type(name: "Query") {
name
}
`,
},
wantReturned_value: nil,
wantErr: true,
},
{
name: "TestBaseClient_Query_tgbotapp_invalid_wrong_field",
graphQLServer: "https://telegram-bot.app/v1/graphql",
args: args{
query: `query {
__type(name: "Query") {
name2
}
}`,
},
wantReturned_value: nil,
wantErr: true,
},
{
name: "TestBaseClient_Query_tgbotapp_wrong_url",
graphQLServer: "https://telegram-bot.app/v0/graphql",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
},
wantReturned_value: nil,
wantErr: true,
},
{
name: "TestBaseClient_Query_tgbotapp_valid_query_mapstring",
graphQLServer: "https://telegram-bot.app/v1/graphql",
wantType: "mapstring",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
},
wantReturned_value: map[string]interface{}{"__type": nil},
wantErr: false,
},
{
name: "TestBaseClient_Query_tgbotapp_valid_query_byte",
graphQLServer: "https://telegram-bot.app/v1/graphql",
wantType: "byte",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
},
wantReturned_value: []byte(`{"__type":null}`),
wantErr: false,
},
{
name: "TestBaseClient_Query_tgbotapp_valid_query_string",
graphQLServer: "https://telegram-bot.app/v1/graphql",
wantType: "string",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
},
wantReturned_value: string(`{"__type":null}`),
wantErr: false,
},
{
name: "TestBaseClient_Query_tgbotapp_valid_query_invalid_type",
graphQLServer: "https://telegram-bot.app/v1/graphql",
wantType: "potato",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
},
wantReturned_value: nil,
wantErr: true,
},
{
name: "TestBaseClient_Query_tgbotapp_valid_query_cache",
graphQLServer: "https://telegram-bot.app/v1/graphql",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
variables: map[string]interface{}{
"gqlcache": true,
},
},
wantReturned_value: string(`{"__type":null}`),
wantErr: false,
},
{
name: "TestBaseClient_Query_tgbotapp_valid_query_with_retry",
graphQLServer: "https://telegram-bot.app/v0/graphql",
wantType: "byte",
args: args{
query: `query {
__type(name: "Query") {
name
}
}`,
variables: map[string]interface{}{
"gqlretries": true,
query: "query { potato { login } ",
variables: nil,
headers: map[string]interface{}{
"x-apollo-operation-name": "InvalidQuery",
"content-type": "application/json",
},
},
wantReturned_value: nil,
@@ -300,9 +167,8 @@ func (suite *Tests) TestBaseClient_Query() {
for _, tt := range tests {
suite.T().Run(tt.name, func(t *testing.T) {
b := NewConnection()
if tt.graphQLServer != "" {
b.SetEndpoint(tt.graphQLServer)
}
b.SetEndpoint(mockServer.URL)
b.SetHTTPClient(mockServer.Client())
if tt.wantType != "" {
b.SetOutput(tt.wantType)
}
+15 -1
View File
@@ -1,6 +1,7 @@
package gql
import (
"net/http/httptest"
"testing"
assertions "github.com/stretchr/testify/assert"
@@ -12,9 +13,22 @@ type Tests struct {
}
var (
assert *assertions.Assertions
assert *assertions.Assertions
mockServer *httptest.Server
)
func (suite *Tests) SetupSuite() {
// Start mock GraphQL server
mockServer = StartMockServer()
}
func (suite *Tests) TearDownSuite() {
// Close the mock server
if mockServer != nil {
mockServer.Close()
}
}
func (suite *Tests) SetupTest() {
assert = assertions.New(suite.T())
}