mirror of
https://github.com/lukaszraczylo/go-simple-graphql.git
synced 2026-10-12 00:45:31 +00:00
Compare commits
32
Commits
@@ -63,7 +63,7 @@ jobs:
|
||||
- name: Run unit tests
|
||||
run: |
|
||||
CI_RUN=${CI} make test
|
||||
git config --global --add safe.directory /__w/graphql-monitoring-proxy/graphql-monitoring-proxy
|
||||
git config --global --add safe.directory /__w/go-simple-graphql/go-simple-graphql
|
||||
|
||||
- name: Commit changes
|
||||
uses: stefanzweifel/git-auto-commit-action@v5
|
||||
|
||||
Vendored
+60
-33
@@ -3,6 +3,7 @@ package libpack_cache
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"hash/fnv"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -13,12 +14,25 @@ type CacheEntry struct {
|
||||
Value []byte
|
||||
}
|
||||
|
||||
const shardCount = 256 // Must be power of 2
|
||||
|
||||
type shard struct {
|
||||
entries map[string]CacheEntry
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
compressPool sync.Pool
|
||||
decompressPool sync.Pool
|
||||
entries sync.Map
|
||||
globalTTL time.Duration
|
||||
sync.RWMutex
|
||||
shards [shardCount]*shard
|
||||
globalTTL time.Duration
|
||||
}
|
||||
|
||||
// getShard returns the appropriate shard for a given key
|
||||
func (c *Cache) getShard(key string) *shard {
|
||||
hash := fnv.New32a()
|
||||
hash.Write([]byte(key))
|
||||
return c.shards[hash.Sum32()%shardCount]
|
||||
}
|
||||
|
||||
func New(globalTTL time.Duration) *Cache {
|
||||
@@ -32,13 +46,19 @@ func New(globalTTL time.Duration) *Cache {
|
||||
},
|
||||
decompressPool: sync.Pool{
|
||||
New: func() interface{} {
|
||||
// Ensure that new is returning a new reader initialized with an empty byte buffer
|
||||
r, _ := gzip.NewReader(bytes.NewReader([]byte{}))
|
||||
return r
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Initialize shards
|
||||
for i := 0; i < shardCount; i++ {
|
||||
cache.shards[i] = &shard{
|
||||
entries: make(map[string]CacheEntry),
|
||||
}
|
||||
}
|
||||
|
||||
go cache.cleanupRoutine(globalTTL)
|
||||
return cache
|
||||
}
|
||||
@@ -52,33 +72,43 @@ func (c *Cache) cleanupRoutine(globalTTL time.Duration) {
|
||||
}
|
||||
}
|
||||
func (c *Cache) Set(key string, value []byte, ttl time.Duration) {
|
||||
c.Lock() // use the lock
|
||||
defer c.Unlock()
|
||||
|
||||
expiresAt := time.Now().Add(ttl)
|
||||
shard := c.getShard(key)
|
||||
shard.Lock()
|
||||
defer shard.Unlock()
|
||||
|
||||
compressedValue, err := c.compress(value)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
entry := CacheEntry{
|
||||
shard.entries[key] = CacheEntry{
|
||||
Value: compressedValue,
|
||||
ExpiresAt: expiresAt,
|
||||
ExpiresAt: time.Now().Add(ttl),
|
||||
}
|
||||
c.entries.Store(key, entry)
|
||||
}
|
||||
|
||||
func (c *Cache) Get(key string) ([]byte, bool) {
|
||||
c.RLock() // use the read lock
|
||||
defer c.RUnlock()
|
||||
|
||||
entry, ok := c.entries.Load(key)
|
||||
if !ok || entry.(CacheEntry).ExpiresAt.Before(time.Now()) {
|
||||
shard := c.getShard(key)
|
||||
shard.RLock()
|
||||
entry, ok := shard.entries[key]
|
||||
if !ok {
|
||||
shard.RUnlock()
|
||||
return nil, false
|
||||
}
|
||||
compressedValue := entry.(CacheEntry).Value
|
||||
value, err := c.decompress(compressedValue)
|
||||
|
||||
if entry.ExpiresAt.Before(time.Now()) {
|
||||
shard.RUnlock()
|
||||
// Clean up expired entry in background
|
||||
go func() {
|
||||
shard.Lock()
|
||||
delete(shard.entries, key)
|
||||
shard.Unlock()
|
||||
}()
|
||||
return nil, false
|
||||
}
|
||||
shard.RUnlock()
|
||||
|
||||
value, err := c.decompress(entry.Value)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
@@ -87,26 +117,23 @@ func (c *Cache) Get(key string) ([]byte, bool) {
|
||||
}
|
||||
|
||||
func (c *Cache) Delete(key string) {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
_, ok := c.entries.Load(key)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
c.entries.Delete(key)
|
||||
shard := c.getShard(key)
|
||||
shard.Lock()
|
||||
delete(shard.entries, key)
|
||||
shard.Unlock()
|
||||
}
|
||||
|
||||
func (c *Cache) CleanExpiredEntries() {
|
||||
now := time.Now()
|
||||
c.entries.Range(func(key, value interface{}) bool {
|
||||
entry := value.(CacheEntry)
|
||||
if entry.ExpiresAt.Before(now) {
|
||||
c.entries.Delete(key)
|
||||
for _, shard := range c.shards {
|
||||
shard.Lock()
|
||||
for key, entry := range shard.entries {
|
||||
if entry.ExpiresAt.Before(now) {
|
||||
delete(shard.entries, key)
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
shard.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cache) compress(data []byte) ([]byte, error) {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
This is a dummy change for PR #1
|
||||
@@ -0,0 +1 @@
|
||||
This is a dummy change for PR #10
|
||||
@@ -0,0 +1 @@
|
||||
This is a dummy change for PR #11
|
||||
@@ -0,0 +1 @@
|
||||
This is a dummy change for PR #12
|
||||
@@ -0,0 +1 @@
|
||||
This is a dummy change for PR #13
|
||||
@@ -0,0 +1 @@
|
||||
This is a dummy change for PR #2
|
||||
@@ -0,0 +1 @@
|
||||
This is a dummy change for PR #3
|
||||
+52
-54
@@ -7,7 +7,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go/v4"
|
||||
@@ -15,11 +14,22 @@ import (
|
||||
libpack_logger "github.com/lukaszraczylo/go-simple-graphql/logging"
|
||||
)
|
||||
|
||||
var bufferPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return new(bytes.Buffer)
|
||||
},
|
||||
}
|
||||
var (
|
||||
// Shared HTTP transport with optimized settings
|
||||
defaultTransport = &http.Transport{
|
||||
MaxIdleConns: 100,
|
||||
MaxIdleConnsPerHost: 100,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
DisableCompression: false, // Enable compression for responses
|
||||
ForceAttemptHTTP2: true,
|
||||
}
|
||||
|
||||
// Shared HTTP client with timeouts
|
||||
defaultClient = &http.Client{
|
||||
Transport: defaultTransport,
|
||||
Timeout: 30 * time.Second,
|
||||
}
|
||||
)
|
||||
|
||||
func (qe *QueryExecutor) executeQuery() ([]byte, error) {
|
||||
// Reuse buffer from pool to avoid allocations
|
||||
@@ -27,16 +37,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 +51,71 @@ 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 {
|
||||
httpResponse, err := qe.client.Do(httpRequest)
|
||||
// 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())
|
||||
|
||||
// Use default client if custom client is not set
|
||||
client := qe.client
|
||||
if client == nil {
|
||||
client = defaultClient
|
||||
}
|
||||
httpResponse, err := 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
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(reader)
|
||||
// Use buffer pool for reading response
|
||||
respBuf := bufferPool.Get().(*bytes.Buffer)
|
||||
respBuf.Reset()
|
||||
defer bufferPool.Put(respBuf)
|
||||
|
||||
_, err = io.Copy(respBuf, 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)
|
||||
}
|
||||
|
||||
err = json.Unmarshal(body, &queryResult)
|
||||
// Unmarshal response directly from buffer
|
||||
err = json.Unmarshal(respBuf.Bytes(), &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)
|
||||
}
|
||||
|
||||
@@ -134,6 +130,7 @@ func (qe *QueryExecutor) executeQuery() ([]byte, error) {
|
||||
retry.Attempts(uint(retriesMax)),
|
||||
retry.DelayType(retry.BackOffDelay),
|
||||
retry.Delay(time.Duration(qe.retries_delay)),
|
||||
retry.MaxDelay(10 * time.Second),
|
||||
retry.LastErrorOnly(true),
|
||||
)
|
||||
if err != nil {
|
||||
@@ -160,6 +157,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{
|
||||
|
||||
@@ -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.5
|
||||
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.11.0 // indirect
|
||||
golang.org/x/sys v0.30.0 // indirect
|
||||
golang.org/x/term v0.29.0 // indirect
|
||||
golang.org/x/text v0.22.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
@@ -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.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/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.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
|
||||
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU=
|
||||
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
|
||||
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
||||
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
||||
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=
|
||||
|
||||
+3
-3
@@ -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[:])
|
||||
}
|
||||
|
||||
@@ -48,6 +48,6 @@ func (b *BaseClient) decodeResponse(response []byte) (any, error) {
|
||||
Message: "Can't decode response",
|
||||
Pairs: map[string]interface{}{"error": "unknown response type"},
|
||||
})
|
||||
return nil, fmt.Errorf("Can't decode response - unknown response type specified")
|
||||
return nil, fmt.Errorf("can't decode response - unknown response type specified")
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,8 +1,9 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/goccy/go-reflect"
|
||||
)
|
||||
|
||||
func (suite *Tests) Test_searchForKeysInMapStringInterface() {
|
||||
|
||||
@@ -58,11 +58,11 @@ func Benchmark_NewLogger(b *testing.B) {
|
||||
got := New()
|
||||
|
||||
if tt.triggers.ModFormat.Format != "" {
|
||||
got = got.SetFormat(tt.triggers.ModFormat.Format)
|
||||
got.SetFormat(tt.triggers.ModFormat.Format)
|
||||
}
|
||||
|
||||
if tt.triggers.ModLevel.Level != 0 {
|
||||
got = got.SetMinLogLevel(tt.triggers.ModLevel.Level)
|
||||
got.SetMinLogLevel(tt.triggers.ModLevel.Level)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
+1
-26
@@ -3,38 +3,13 @@ package libpack_logger
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/goccy/go-json"
|
||||
"github.com/goccy/go-reflect"
|
||||
)
|
||||
|
||||
func captureStderr(f func()) string {
|
||||
originalStderr := os.Stderr
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stderr = w
|
||||
f()
|
||||
w.Close()
|
||||
var buf bytes.Buffer
|
||||
buf.ReadFrom(r)
|
||||
os.Stderr = originalStderr
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func captureStdOut(f func()) string {
|
||||
originalStdout := os.Stdout
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stdout = w
|
||||
f()
|
||||
w.Close()
|
||||
var buf bytes.Buffer
|
||||
buf.ReadFrom(r)
|
||||
os.Stdout = originalStdout
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func (suite *LoggerTestSuite) Test_LogMessageString() {
|
||||
msg := &LogMessage{
|
||||
Message: "test message",
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// mock_server.go
|
||||
package gql
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"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 := io.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
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
// Pre-sized buffer pool for better performance
|
||||
bufferPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
// Pre-allocate buffer with 4KB capacity
|
||||
b := bytes.NewBuffer(make([]byte, 0, 4096))
|
||||
return b
|
||||
},
|
||||
}
|
||||
|
||||
// Pre-allocate error maps to reduce allocations
|
||||
errPairsPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make(map[string]interface{}, 1)
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -1,8 +1,8 @@
|
||||
package gql
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/goccy/go-json"
|
||||
"github.com/gookit/goutil"
|
||||
@@ -10,55 +10,74 @@ 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)
|
||||
buf := bufferPool.Get().(*bytes.Buffer)
|
||||
defer bufferPool.Put(buf)
|
||||
buf.Reset()
|
||||
|
||||
*jsonBuffer = (*jsonBuffer)[:0]
|
||||
jsonData, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
// Use json.NewEncoder for better performance with buffers
|
||||
enc := json.NewEncoder(buf)
|
||||
enc.SetEscapeHTML(false) // Reduce unnecessary escaping
|
||||
|
||||
if err := enc.Encode(v); err != nil {
|
||||
errPairs := errPairsPool.Get().(map[string]interface{})
|
||||
errPairs["error"] = err.Error()
|
||||
b.Logger.Error(&libpack_logger.LogMessage{
|
||||
Message: "Can't convert to JSON",
|
||||
Pairs: map[string]interface{}{"error": err.Error()},
|
||||
Pairs: errPairs,
|
||||
})
|
||||
errPairsPool.Put(errPairs)
|
||||
return nil
|
||||
}
|
||||
*jsonBuffer = append(*jsonBuffer, jsonData...)
|
||||
return *jsonBuffer
|
||||
|
||||
// Get the buffer bytes directly, trimming the trailing newline
|
||||
bytes := buf.Bytes()
|
||||
if len(bytes) > 0 && bytes[len(bytes)-1] == '\n' {
|
||||
bytes = bytes[:len(bytes)-1]
|
||||
}
|
||||
|
||||
// Make a copy of the bytes since the buffer will be reused
|
||||
result := make([]byte, len(bytes))
|
||||
copy(result, bytes)
|
||||
return result
|
||||
}
|
||||
|
||||
func (b *BaseClient) compileQuery(queryPartials ...any) *Query {
|
||||
var query string
|
||||
var variables map[string]interface{}
|
||||
for _, partial := range queryPartials {
|
||||
switch val := partial.(type) {
|
||||
case string:
|
||||
query = val
|
||||
case map[string]interface{}:
|
||||
variables = val
|
||||
|
||||
// Pre-allocate the query with an estimated size
|
||||
if len(queryPartials) > 0 {
|
||||
if str, ok := queryPartials[0].(string); ok {
|
||||
query = str
|
||||
}
|
||||
}
|
||||
|
||||
// Only allocate variables map if we have more than one partial
|
||||
if len(queryPartials) > 1 {
|
||||
if vars, ok := queryPartials[1].(map[string]interface{}); ok {
|
||||
variables = vars
|
||||
}
|
||||
}
|
||||
|
||||
if query == "" {
|
||||
errPairs := errPairsPool.Get().(map[string]interface{})
|
||||
errPairs["error"] = "query is empty"
|
||||
b.Logger.Error(&libpack_logger.LogMessage{
|
||||
Message: "Can't compile query",
|
||||
Pairs: map[string]interface{}{"error": "query is empty"},
|
||||
Pairs: errPairs,
|
||||
})
|
||||
errPairsPool.Put(errPairs)
|
||||
return nil
|
||||
}
|
||||
|
||||
jsonQuery := b.convertToJSON(&Query{Query: query, Variables: variables})
|
||||
return &Query{
|
||||
// Construct query object once
|
||||
q := &Query{
|
||||
Query: query,
|
||||
Variables: variables,
|
||||
JsonQuery: jsonQuery,
|
||||
}
|
||||
q.JsonQuery = b.convertToJSON(q)
|
||||
return q
|
||||
}
|
||||
|
||||
func (b *BaseClient) Query(query string, variables map[string]interface{}, headers map[string]interface{}) (any, error) {
|
||||
@@ -92,7 +111,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 +119,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 +141,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
@@ -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
@@ -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
@@ -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())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user