mirror of
https://github.com/lukaszraczylo/go-simple-graphql.git
synced 2026-10-13 00:48:37 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
edc695fe2b
|
||
|
|
bd0c5ec373
|
||
|
|
952749d7ff
|
||
|
|
277ef21263
|
||
|
|
4980aeb28a
|
||
|
|
91f65ebd46
|
||
|
|
d5655ae2fa
|
||
|
|
9b65ba069f
|
||
|
|
feed2f36c2
|
||
|
|
966d9ccd0a
|
||
|
|
3232498e94
|
||
|
|
3cda8e267b
|
||
|
|
1393f4d7cf
|
||
|
|
d4328fdbb7
|
||
|
|
4ac9f132a2
|
||
|
|
fb04e68b8d
|
||
|
|
40652c3fdd
|
||
|
|
f360a5cf7e
|
||
|
|
2b09da7685
|
||
|
|
aac6ca113d
|
||
|
|
c8ed2290b4
|
||
|
|
d1406eeac8
|
||
|
|
ea7ec683ef
|
||
|
|
5cd22318f1
|
+2
-1
@@ -1,3 +1,4 @@
|
|||||||
*.out
|
*.out
|
||||||
*.test
|
*.test
|
||||||
coverage.txt
|
coverage.txt
|
||||||
|
*.DS_Store
|
||||||
@@ -22,4 +22,11 @@ all: test-packages test
|
|||||||
|
|
||||||
.PHONY: update
|
.PHONY: update
|
||||||
update: ## update dependencies
|
update: ## update dependencies
|
||||||
@go get -u -v ./...
|
@go get -u -v ./...
|
||||||
|
|
||||||
|
sonar:
|
||||||
|
sonar-scanner \
|
||||||
|
-Dsonar.projectKey=golang-simple-graphql \
|
||||||
|
-Dsonar.sources=. \
|
||||||
|
-Dsonar.host.url=http://localhost:9000 \
|
||||||
|
-Dsonar.login=555ba78b315faa07b3231a3be0f3cbb24ab33814
|
||||||
@@ -14,8 +14,8 @@ Ps. It's Hasura friendly.
|
|||||||
|
|
||||||
## Reasoning
|
## Reasoning
|
||||||
|
|
||||||
I've tried to run few graphQL clients with hasura, all of them required conversion of the data into
|
I've tried to run a few GraphQL clients with Hasura, all of them required conversion of the data into
|
||||||
the appropriate structures, causing issues with non-existing types ( thanks to Hasura ), for example `bigint` which was difficult to export.
|
the appropriate structures, causing issues with non-existing types ( thanks to Hasura ), for example, `bigint` which was difficult to export.
|
||||||
Therefore, I present you the simple client to which you can copy & paste your graphQL query, variables and you are good to go.
|
Therefore, I present you the simple client to which you can copy & paste your graphQL query, variables and you are good to go.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
@@ -23,13 +23,19 @@ Therefore, I present you the simple client to which you can copy & paste your gr
|
|||||||
* Executing GraphQL queries as they are, without types declaration
|
* Executing GraphQL queries as they are, without types declaration
|
||||||
* HTTP2 support!
|
* HTTP2 support!
|
||||||
* Support for additional headers
|
* Support for additional headers
|
||||||
|
* Query cache
|
||||||
|
|
||||||
## Usage example
|
## Usage example
|
||||||
|
|
||||||
### Environment variables
|
### Environment variables
|
||||||
|
|
||||||
* `GRAPHQL_ENDPOINT` - Your GraphQL endpoint. Default: `http://127.0.0.1:9090/v1/graphql`
|
* `GRAPHQL_ENDPOINT` - Your GraphQL endpoint. Default: `http://127.0.0.1:9090/v1/graphql`
|
||||||
|
* `GRAPHQL_CACHE` - Should the query cache be enabled? Default: `false`
|
||||||
|
* `GRAPHQL_CACHE_TTL` - Cache TTL in seconds for SELECT type of queries. Default: `5`
|
||||||
* `LOG_LEVEL` - Logging level. Default: `info`
|
* `LOG_LEVEL` - Logging level. Default: `info`
|
||||||
|
* `RETRIES_ENABLE` - Should retries be enabled? Default: `false`
|
||||||
|
* `RETRIES_NUMBER` - Number of retries: Default: `1`
|
||||||
|
* `RETRIES_DELAY` - Delay in retries in milliseconds. Default: `250`
|
||||||
|
|
||||||
### Example reader code
|
### Example reader code
|
||||||
|
|
||||||
@@ -37,28 +43,28 @@ Therefore, I present you the simple client to which you can copy & paste your gr
|
|||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
fmt
|
fmt
|
||||||
gql "github.com/lukaszraczylo/simple-gql-client"
|
graphql "github.com/lukaszraczylo/go-simple-graphql"
|
||||||
)
|
)
|
||||||
|
|
||||||
headers := map[string]interface{}{
|
headers := map[string]interface{}{
|
||||||
"x-hasura-user-id": 37,
|
"x-hasura-user-id": 37,
|
||||||
"x-hasura-user-uuid": "bde3262e-b42e-4151-ac10-d43f0bef44a5",
|
"x-hasura-user-uuid": "bde1962e-b42e-1212-ac10-d43fa27f44a5",
|
||||||
}
|
}
|
||||||
|
|
||||||
variables := map[string]interface{}{
|
variables := map[string]interface{}{
|
||||||
"fileHash": "123deadc0w321",
|
"fileHash": "123deadc0w321",
|
||||||
}
|
}
|
||||||
var query = `query searchFileKnown($fileHash: String) {
|
|
||||||
|
query := `query searchFileKnown($fileHash: String) {
|
||||||
tbl_file_scans(where: {file_hash: {_eq: $fileHash}}) {
|
tbl_file_scans(where: {file_hash: {_eq: $fileHash}}) {
|
||||||
porn
|
|
||||||
racy
|
racy
|
||||||
violence
|
violence
|
||||||
virus
|
virus
|
||||||
}
|
}
|
||||||
}
|
}`
|
||||||
|
|
||||||
graphql := NewConnection()
|
gql := graphql.NewConnection()
|
||||||
result, err := graphql.Query(query, variables, nil)
|
result, err := gql.Query(query, variables, headers)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("Query error", err)
|
fmt.Println("Query error", err)
|
||||||
return
|
return
|
||||||
@@ -74,10 +80,10 @@ fmt.Println(result)
|
|||||||
|
|
||||||
## Working with results
|
## Working with results
|
||||||
|
|
||||||
I'm using an amazing library [tidwall/gjson](https://github.com/tidwall/gjson) to parse the results and extract information required in further steps and I strongly recommend this approach as the easiest and close to painless.
|
I'm using an amazing library [tidwall/gjson](https://github.com/tidwall/gjson) to parse the results and extract the information required in further steps and I strongly recommend this approach as the easiest and close to painless, for example:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
result = gjson.Get(result, "tbl_user_group_admins.0.is_admin").Bool()
|
result := gjson.Get(result, "tbl_user_group_admins.0.is_admin").Bool()
|
||||||
if result {
|
if result {
|
||||||
fmt.Println("User is an admin")
|
fmt.Println("User is an admin")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,31 @@
|
|||||||
module github.com/lukaszraczylo/go-simple-graphql
|
module github.com/lukaszraczylo/go-simple-graphql
|
||||||
|
|
||||||
go 1.17
|
go 1.18
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/allegro/bigcache/v3 v3.0.1
|
github.com/allegro/bigcache/v3 v3.1.0
|
||||||
github.com/buger/jsonparser v1.1.1
|
github.com/avast/retry-go v3.0.0+incompatible
|
||||||
github.com/json-iterator/go v1.1.12
|
github.com/json-iterator/go v1.1.12
|
||||||
github.com/lukaszraczylo/pandati v0.0.10
|
github.com/lukaszraczylo/pandati v0.0.15
|
||||||
github.com/rs/zerolog v1.26.0
|
github.com/rs/zerolog v1.28.0
|
||||||
github.com/stretchr/testify v1.7.0
|
github.com/sethvargo/go-retry v0.2.4
|
||||||
golang.org/x/net v0.0.0-20211201190559-0a0e4e1bb54c
|
github.com/stretchr/testify v1.7.1
|
||||||
|
golang.org/x/net v0.4.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
github.com/imdario/mergo v0.3.12 // indirect
|
github.com/imdario/mergo v0.3.13 // indirect
|
||||||
github.com/kr/pretty v0.1.0 // indirect
|
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.16 // indirect
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
golang.org/x/text v0.3.7 // indirect
|
github.com/tidwall/gjson v1.14.4 // indirect
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
|
github.com/tidwall/match v1.1.1 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect
|
github.com/tidwall/pretty v1.2.1 // indirect
|
||||||
|
github.com/wI2L/jsondiff v0.3.0 // indirect
|
||||||
|
golang.org/x/sys v0.3.0 // indirect
|
||||||
|
golang.org/x/text v0.5.0 // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.0 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,24 +1,25 @@
|
|||||||
github.com/allegro/bigcache/v3 v3.0.1 h1:Q4Xl3chywXuJNOw7NV+MeySd3zGQDj4KCpkCg0te8mc=
|
github.com/allegro/bigcache/v3 v3.1.0 h1:H2Vp8VOvxcrB91o86fUSVJFqeuz8kpyyB02eH3bSzwk=
|
||||||
github.com/allegro/bigcache/v3 v3.0.1/go.mod h1:aPyh7jEvrog9zAwx5N7+JUQX5dZTSGpxF1LAR4dr35I=
|
github.com/allegro/bigcache/v3 v3.1.0/go.mod h1:aPyh7jEvrog9zAwx5N7+JUQX5dZTSGpxF1LAR4dr35I=
|
||||||
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
|
github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0=
|
||||||
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY=
|
||||||
github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
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/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU=
|
github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk=
|
||||||
github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
|
github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg=
|
||||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
github.com/lukaszraczylo/pandati v0.0.15 h1:1BNtbmhIQbKgs1Gm9WlH3CMms+TgkgxZcU7utHbjloY=
|
||||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
github.com/lukaszraczylo/pandati v0.0.15/go.mod h1:5E0mqlNgdOps6FW2X4tPilr+3B8s9JGWFgA6ZVFixyQ=
|
||||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
|
||||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||||
github.com/lukaszraczylo/pandati v0.0.10 h1:ZXmLjxb/UYRBVyAKwXmUcJgZ2FYNwGY4YDJsQQMYAXI=
|
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||||
github.com/lukaszraczylo/pandati v0.0.10/go.mod h1:1lE/x4X4LfO1yerAQoiR7AVb/wIabH/zITDGnqTdyH8=
|
github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
|
||||||
|
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
@@ -27,44 +28,35 @@ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjY
|
|||||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
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/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||||
github.com/rs/zerolog v1.26.0 h1:ORM4ibhEZeTeQlCojCK2kPz1ogAY4bGs4tD+SaAdGaE=
|
github.com/rs/zerolog v1.28.0 h1:MirSo27VyNi7RJYP3078AA1+Cyzd2GB66qy3aUHvsWY=
|
||||||
github.com/rs/zerolog v1.26.0/go.mod h1:yBiM87lvSqX8h0Ww4sdzNSkVYZ8dL2xjZJG1lAuGZEo=
|
github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0=
|
||||||
|
github.com/sethvargo/go-retry v0.2.4 h1:T+jHEQy/zKJf5s95UkguisicE0zuF9y7+/vgz08Ocec=
|
||||||
|
github.com/sethvargo/go-retry v0.2.4/go.mod h1:1afjQuvh7s4gflMObvjLPaWgluLLyhA1wmVZ6KLpICw=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
github.com/tidwall/gjson v1.14.4 h1:uo0p8EbA09J7RQaflQ1aBRffTR7xedD2bcIVSYxLnkM=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||||
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
||||||
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||||
golang.org/x/net v0.0.0-20211201190559-0a0e4e1bb54c h1:WtYZ93XtWSO5KlOMgPZu7hXY9WhMZpprvlm5VwvAl8c=
|
github.com/wI2L/jsondiff v0.3.0 h1:iTzQ9u/d86GE9RsBzVHX88f2EA1vQUboHwLhSQFc1s4=
|
||||||
golang.org/x/net v0.0.0-20211201190559-0a0e4e1bb54c/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
github.com/wI2L/jsondiff v0.3.0/go.mod h1:y1IMzNNjlSsk3IUoJdRJO7VRBtzMvRgyo4Vu0LdHpTc=
|
||||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/net v0.4.0 h1:Q5QPcMlvfxFTAPV0+07Xz/MpK9NTXu2VDUuy0FeMfaU=
|
||||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
|
||||||
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM=
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
|
|
||||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
|
||||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
|
||||||
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
|
|
||||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
|
||||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
|
||||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
|
||||||
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
|
|
||||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0 h1:hjy8E9ON/egN1tAYqKb61G10WtihqetD4sz2H+8nIeA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
@@ -15,14 +15,15 @@ package gql
|
|||||||
import (
|
import (
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/allegro/bigcache/v3"
|
bigcache "github.com/allegro/bigcache/v3"
|
||||||
jsoniter "github.com/json-iterator/go"
|
jsoniter "github.com/json-iterator/go"
|
||||||
"github.com/lukaszraczylo/go-simple-graphql/pkg/logging"
|
"github.com/lukaszraczylo/go-simple-graphql/pkg/logging"
|
||||||
|
retry "github.com/sethvargo/go-retry"
|
||||||
"golang.org/x/net/http2"
|
"golang.org/x/net/http2"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -31,11 +32,15 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type GraphQL struct {
|
type GraphQL struct {
|
||||||
Endpoint string
|
Endpoint string
|
||||||
HttpClient *http.Client
|
HttpClient *http.Client
|
||||||
Log *logging.LogConfig
|
Log *logging.LogConfig
|
||||||
Cache bool // Enable caching for read queries
|
Cache bool // Enable caching for read queries
|
||||||
CacheStore *bigcache.BigCache
|
CacheStore *bigcache.BigCache
|
||||||
|
RetriesEnable bool
|
||||||
|
RetriesNumber int
|
||||||
|
RetriesDelay time.Duration
|
||||||
|
BackoffSetup retry.Backoff
|
||||||
}
|
}
|
||||||
|
|
||||||
func pickGraphqlEndpoint() (graphqlEndpoint string) {
|
func pickGraphqlEndpoint() (graphqlEndpoint string) {
|
||||||
@@ -49,27 +54,85 @@ func pickGraphqlEndpoint() (graphqlEndpoint string) {
|
|||||||
return graphqlEndpoint
|
return graphqlEndpoint
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewConnection() *GraphQL {
|
func setCacheTTL() int {
|
||||||
return &GraphQL{
|
value, present := os.LookupEnv("GRAPHQL_CACHE_TTL")
|
||||||
Endpoint: pickGraphqlEndpoint(),
|
if present && value != "" {
|
||||||
HttpClient: &http.Client{
|
i, err := strconv.Atoi(value)
|
||||||
Transport: &http2.Transport{
|
if err != nil {
|
||||||
DisableCompression: false,
|
panic("Invalid value for query cache ttl")
|
||||||
AllowHTTP: true,
|
}
|
||||||
PingTimeout: 5 * time.Second,
|
return int(i)
|
||||||
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
|
} else {
|
||||||
return net.Dial(network, addr)
|
return 5
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Log: logging.NewLogger(),
|
|
||||||
Cache: false,
|
|
||||||
CacheStore: setupCache(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func setCacheEnabled() bool {
|
||||||
|
value, present := os.LookupEnv("GRAPHQL_CACHE")
|
||||||
|
if present && value != "" {
|
||||||
|
b, err := strconv.ParseBool(value)
|
||||||
|
if err != nil {
|
||||||
|
panic("Invalid value for query cache")
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
} else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConnection() *GraphQL {
|
||||||
|
g := GraphQL{
|
||||||
|
Endpoint: pickGraphqlEndpoint(),
|
||||||
|
HttpClient: &http.Client{
|
||||||
|
Transport: &http2.Transport{
|
||||||
|
ReadIdleTimeout: 30 * time.Second,
|
||||||
|
DisableCompression: false,
|
||||||
|
AllowHTTP: true,
|
||||||
|
PingTimeout: 5 * time.Second,
|
||||||
|
TLSClientConfig: &tls.Config{
|
||||||
|
InsecureSkipVerify: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Log: logging.NewLogger(),
|
||||||
|
Cache: setCacheEnabled(),
|
||||||
|
CacheStore: setupCache(),
|
||||||
|
RetriesEnable: false,
|
||||||
|
RetriesNumber: 1,
|
||||||
|
RetriesDelay: 250,
|
||||||
|
BackoffSetup: nil,
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
retriesEnable, retriesEnableExists := os.LookupEnv("RETRIES_ENABLE")
|
||||||
|
if retriesEnableExists {
|
||||||
|
g.RetriesEnable, err = strconv.ParseBool(retriesEnable)
|
||||||
|
if err != nil {
|
||||||
|
panic("Invalid value for RETRIES_ENABLE")
|
||||||
|
}
|
||||||
|
retriesNumber, retriesNumberExists := os.LookupEnv("RETRIES_NUMBER")
|
||||||
|
if retriesNumberExists {
|
||||||
|
g.RetriesNumber, err = strconv.Atoi(retriesNumber)
|
||||||
|
if err != nil {
|
||||||
|
panic("Invalid value for RETRIES_NUMBER")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
retriesDelay, retriesDelayExists := os.LookupEnv("RETRIES_DELAY")
|
||||||
|
if retriesDelayExists {
|
||||||
|
retDel, err := strconv.Atoi(retriesDelay)
|
||||||
|
if err != nil {
|
||||||
|
panic("Invalid value for RETRIES_DELAY")
|
||||||
|
}
|
||||||
|
g.RetriesDelay = time.Duration(retDel) * time.Millisecond
|
||||||
|
}
|
||||||
|
}
|
||||||
|
g.BackoffSetup = retry.NewExponential(g.RetriesDelay)
|
||||||
|
g.BackoffSetup = retry.WithMaxRetries(uint64(g.RetriesNumber), g.BackoffSetup)
|
||||||
|
|
||||||
|
return &g
|
||||||
|
}
|
||||||
|
|
||||||
func setupCache() *bigcache.BigCache {
|
func setupCache() *bigcache.BigCache {
|
||||||
cache, err := bigcache.NewBigCache(bigcache.DefaultConfig(10 * time.Second))
|
cache, err := bigcache.NewBigCache(bigcache.DefaultConfig(time.Duration(setCacheTTL()) * time.Second))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic("Error creating cache: " + err.Error())
|
panic("Error creating cache: " + err.Error())
|
||||||
}
|
}
|
||||||
|
|||||||
+28
-33
@@ -6,7 +6,6 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/lukaszraczylo/pandati"
|
|
||||||
"github.com/rs/zerolog"
|
"github.com/rs/zerolog"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -17,14 +16,14 @@ type LogConfig struct {
|
|||||||
|
|
||||||
func NewLogger() *LogConfig {
|
func NewLogger() *LogConfig {
|
||||||
log := new(LogConfig)
|
log := new(LogConfig)
|
||||||
switch dll := os.Getenv("LOG_LEVEL"); dll {
|
dll := os.Getenv("LOG_LEVEL")
|
||||||
case "debug":
|
if dll == "debug" {
|
||||||
zerolog.SetGlobalLevel(zerolog.DebugLevel)
|
zerolog.SetGlobalLevel(zerolog.DebugLevel)
|
||||||
case "warn":
|
} else if dll == "warn" {
|
||||||
zerolog.SetGlobalLevel(zerolog.WarnLevel)
|
zerolog.SetGlobalLevel(zerolog.WarnLevel)
|
||||||
case "error":
|
} else if dll == "error" {
|
||||||
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
|
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
|
||||||
default:
|
} else {
|
||||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||||
}
|
}
|
||||||
zerolog.TimeFieldFormat = time.RFC3339
|
zerolog.TimeFieldFormat = time.RFC3339
|
||||||
@@ -37,36 +36,12 @@ func NewLogger() *LogConfig {
|
|||||||
return log
|
return log
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *LogConfig) Critical(message string, v ...map[string]interface{}) {
|
func (l *LogConfig) Log(level zerolog.Level, message string, v ...map[string]interface{}) {
|
||||||
w := l.Logger.Output(os.Stderr)
|
contextLog := l.Logger.WithLevel(level)
|
||||||
log(w.Fatal(), message, v...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *LogConfig) Error(message string, v ...map[string]interface{}) {
|
|
||||||
w := l.Logger.Output(os.Stderr)
|
|
||||||
log(w.Error(), message, v...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *LogConfig) Warning(message string, v ...map[string]interface{}) {
|
|
||||||
w := l.Logger.Output(os.Stdout)
|
|
||||||
log(w.Warn(), message, v...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *LogConfig) Info(message string, v ...map[string]interface{}) {
|
|
||||||
w := l.Logger.Output(os.Stdout)
|
|
||||||
log(w.Info(), message, v...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *LogConfig) Debug(message string, v ...map[string]interface{}) {
|
|
||||||
w := l.Logger.Output(os.Stdout)
|
|
||||||
log(w.Debug(), message, v...)
|
|
||||||
}
|
|
||||||
|
|
||||||
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) && !pandati.IsZero(k) {
|
if v != nil && k != "" {
|
||||||
contextLog.Str(k, fmt.Sprintf("%v", v))
|
contextLog.Str(k, fmt.Sprintf("%v", v))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -75,3 +50,23 @@ func log(contextLog *zerolog.Event, message string, v ...map[string]interface{})
|
|||||||
// contextLog.Str("_stack_trace", pandati.Trace())
|
// contextLog.Str("_stack_trace", pandati.Trace())
|
||||||
contextLog.Msg(message)
|
contextLog.Msg(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (l *LogConfig) Critical(message string, v ...map[string]interface{}) {
|
||||||
|
l.Log(zerolog.FatalLevel, message, v...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *LogConfig) Error(message string, v ...map[string]interface{}) {
|
||||||
|
l.Log(zerolog.ErrorLevel, message, v...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *LogConfig) Warning(message string, v ...map[string]interface{}) {
|
||||||
|
l.Log(zerolog.WarnLevel, message, v...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *LogConfig) Info(message string, v ...map[string]interface{}) {
|
||||||
|
l.Log(zerolog.InfoLevel, message, v...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *LogConfig) Debug(message string, v ...map[string]interface{}) {
|
||||||
|
l.Log(zerolog.DebugLevel, message, v...)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,373 +0,0 @@
|
|||||||
package logging
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
|
||||||
"reflect"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/buger/jsonparser"
|
|
||||||
"github.com/stretchr/testify/suite"
|
|
||||||
)
|
|
||||||
|
|
||||||
type LoggingTestSuite struct {
|
|
||||||
suite.Suite
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
testsLogger *LogConfig
|
|
||||||
)
|
|
||||||
|
|
||||||
type stdoutCapture struct {
|
|
||||||
oldStdout *os.File
|
|
||||||
readPipe *os.File
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sc *stdoutCapture) StartCapture() {
|
|
||||||
sc.oldStdout = os.Stdout
|
|
||||||
sc.readPipe, os.Stdout, _ = os.Pipe()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sc *stdoutCapture) StopCapture() (string, error) {
|
|
||||||
if sc.oldStdout == nil || sc.readPipe == nil {
|
|
||||||
return "", errors.New("StartCapture not called before StopCapture on Stdout")
|
|
||||||
}
|
|
||||||
os.Stdout.Close()
|
|
||||||
os.Stdout = sc.oldStdout
|
|
||||||
bytes, err := ioutil.ReadAll(sc.readPipe)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return string(bytes), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type stderrCapture struct {
|
|
||||||
oldStderr *os.File
|
|
||||||
readPipe *os.File
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sc *stderrCapture) StartCapture() {
|
|
||||||
sc.oldStderr = os.Stderr
|
|
||||||
sc.readPipe, os.Stderr, _ = os.Pipe()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sc *stderrCapture) StopCapture() (string, error) {
|
|
||||||
if sc.oldStderr == nil || sc.readPipe == nil {
|
|
||||||
return "", errors.New("StartCapture not called before StopCapture on Stderr")
|
|
||||||
}
|
|
||||||
os.Stderr.Close()
|
|
||||||
os.Stderr = sc.oldStderr
|
|
||||||
bytes, err := ioutil.ReadAll(sc.readPipe)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return string(bytes), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (suite *LoggingTestSuite) SetupTest() {
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoggingTestSuite(t *testing.T) {
|
|
||||||
suite.Run(t, new(LoggingTestSuite))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (suite *LoggingTestSuite) TestLogConfig_AllHandlers() {
|
|
||||||
type args struct {
|
|
||||||
message string
|
|
||||||
}
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
args args
|
|
||||||
wantLevel string
|
|
||||||
wantMessage string
|
|
||||||
envMinLogLevel string
|
|
||||||
stdOutExpect bool
|
|
||||||
stdErrExpect bool
|
|
||||||
loggerType string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "Test log: Error",
|
|
||||||
loggerType: "Error",
|
|
||||||
args: args{
|
|
||||||
message: "This is a error message",
|
|
||||||
},
|
|
||||||
wantLevel: "error",
|
|
||||||
wantMessage: "This is a error message",
|
|
||||||
stdErrExpect: true,
|
|
||||||
stdOutExpect: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Test log: Warning",
|
|
||||||
loggerType: "Warning",
|
|
||||||
args: args{
|
|
||||||
message: "This is a warning message",
|
|
||||||
},
|
|
||||||
wantLevel: "warn",
|
|
||||||
wantMessage: "This is a warning message",
|
|
||||||
stdErrExpect: false,
|
|
||||||
stdOutExpect: true,
|
|
||||||
envMinLogLevel: "info",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Test log: Warning | Min level: Debug",
|
|
||||||
loggerType: "Warning",
|
|
||||||
args: args{
|
|
||||||
message: "This is a warning message",
|
|
||||||
},
|
|
||||||
wantLevel: "warn",
|
|
||||||
wantMessage: "This is a warning message",
|
|
||||||
stdErrExpect: false,
|
|
||||||
stdOutExpect: true,
|
|
||||||
envMinLogLevel: "debug",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Test log: Info",
|
|
||||||
loggerType: "Info",
|
|
||||||
args: args{
|
|
||||||
message: "This is a info message",
|
|
||||||
},
|
|
||||||
wantLevel: "info",
|
|
||||||
wantMessage: "This is a info message",
|
|
||||||
stdErrExpect: false,
|
|
||||||
stdOutExpect: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Test log: Info | Min level: Warn",
|
|
||||||
loggerType: "Info",
|
|
||||||
args: args{
|
|
||||||
message: "This is a info message",
|
|
||||||
},
|
|
||||||
wantLevel: "",
|
|
||||||
wantMessage: "",
|
|
||||||
stdErrExpect: false,
|
|
||||||
stdOutExpect: false,
|
|
||||||
envMinLogLevel: "warn",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Test log: Warning | Min level: Warn",
|
|
||||||
loggerType: "Warning",
|
|
||||||
args: args{
|
|
||||||
message: "This is a warning message",
|
|
||||||
},
|
|
||||||
wantLevel: "warn",
|
|
||||||
wantMessage: "This is a warning message",
|
|
||||||
stdErrExpect: false,
|
|
||||||
stdOutExpect: true,
|
|
||||||
envMinLogLevel: "warn",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Test log: Warning | Min level: Error",
|
|
||||||
loggerType: "Warning",
|
|
||||||
args: args{
|
|
||||||
message: "This is an error message",
|
|
||||||
},
|
|
||||||
wantLevel: "",
|
|
||||||
wantMessage: "",
|
|
||||||
stdErrExpect: false,
|
|
||||||
stdOutExpect: false,
|
|
||||||
envMinLogLevel: "error",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Test log: Debug | Min level: Debug",
|
|
||||||
loggerType: "Debug",
|
|
||||||
args: args{
|
|
||||||
message: "This is a debug message",
|
|
||||||
},
|
|
||||||
wantLevel: "debug",
|
|
||||||
wantMessage: "This is a debug message",
|
|
||||||
stdErrExpect: false,
|
|
||||||
stdOutExpect: true,
|
|
||||||
envMinLogLevel: "debug",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
suite.T().Run(tt.name, func(t *testing.T) {
|
|
||||||
if tt.envMinLogLevel != "" {
|
|
||||||
os.Setenv("LOG_LEVEL", tt.envMinLogLevel)
|
|
||||||
defer os.Unsetenv("LOG_LEVEL")
|
|
||||||
}
|
|
||||||
testsLogger = NewLogger()
|
|
||||||
|
|
||||||
captureStdout := stdoutCapture{}
|
|
||||||
captureStdout.StartCapture()
|
|
||||||
captureStderr := stderrCapture{}
|
|
||||||
captureStderr.StartCapture()
|
|
||||||
|
|
||||||
reflect.ValueOf(testsLogger).MethodByName(tt.loggerType).Call([]reflect.Value{reflect.ValueOf(tt.args.message)})
|
|
||||||
|
|
||||||
stdoutOut, err := captureStdout.StopCapture()
|
|
||||||
if err != nil {
|
|
||||||
suite.T().Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
stderrOut, err := captureStderr.StopCapture()
|
|
||||||
if err != nil {
|
|
||||||
suite.T().Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if tt.stdErrExpect && !tt.stdOutExpect {
|
|
||||||
gotLvl, gotMsg, err := getResponseValues(stderrOut, "short_message")
|
|
||||||
suite.NoError(err, "Failed in [STDERR]: "+tt.name)
|
|
||||||
suite.Equal(tt.wantLevel, gotLvl, "Failed in [STDERR]: "+tt.name)
|
|
||||||
suite.Equal(tt.wantMessage, gotMsg, "Failed in [STDERR]: "+tt.name)
|
|
||||||
suite.Equal("", stdoutOut, "Failed in [STDERR]: "+tt.name)
|
|
||||||
}
|
|
||||||
if tt.stdOutExpect && !tt.stdErrExpect {
|
|
||||||
gotLvl, gotMsg, err := getResponseValues(stdoutOut, "short_message")
|
|
||||||
suite.NoError(err, "Failed in [STDOUT]: "+tt.name)
|
|
||||||
suite.Equal(tt.wantLevel, gotLvl, "Failed in [STDOUT]: "+tt.name)
|
|
||||||
suite.Equal(tt.wantMessage, gotMsg, "Failed in [STDOUT]: "+tt.name)
|
|
||||||
suite.Equal("", stderrOut, "Failed in [STDOUT]: "+tt.name)
|
|
||||||
}
|
|
||||||
if !tt.stdErrExpect && !tt.stdOutExpect {
|
|
||||||
suite.Equal("", stderrOut, "Failed in [NEITHER]: "+tt.name)
|
|
||||||
suite.Equal("", stdoutOut, "Failed in [NEITHER]: "+tt.name)
|
|
||||||
}
|
|
||||||
os.Unsetenv("LOG_LEVEL")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (suite *LoggingTestSuite) TestFullMessage() {
|
|
||||||
type args struct {
|
|
||||||
message string
|
|
||||||
extraFields map[string]interface{}
|
|
||||||
}
|
|
||||||
extraFields := make(map[string]interface{})
|
|
||||||
extraFields["_full_message"] = "full message"
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
args args
|
|
||||||
wantLevel string
|
|
||||||
wantMessage string
|
|
||||||
envMinLogLevel string
|
|
||||||
stdOutExpect bool
|
|
||||||
stdErrExpect bool
|
|
||||||
loggerType string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "Test log: Error",
|
|
||||||
loggerType: "Error",
|
|
||||||
args: args{
|
|
||||||
message: "This is a error message",
|
|
||||||
extraFields: extraFields,
|
|
||||||
},
|
|
||||||
wantLevel: "error",
|
|
||||||
wantMessage: extraFields["_full_message"].(string),
|
|
||||||
stdErrExpect: true,
|
|
||||||
stdOutExpect: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Test log: Info",
|
|
||||||
loggerType: "Info",
|
|
||||||
args: args{
|
|
||||||
message: "This is a info message",
|
|
||||||
extraFields: extraFields,
|
|
||||||
},
|
|
||||||
wantMessage: extraFields["_full_message"].(string),
|
|
||||||
stdErrExpect: false,
|
|
||||||
stdOutExpect: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
suite.T().Run(tt.name, func(t *testing.T) {
|
|
||||||
if tt.envMinLogLevel != "" {
|
|
||||||
os.Setenv("LOG_LEVEL", tt.envMinLogLevel)
|
|
||||||
defer os.Unsetenv("LOG_LEVEL")
|
|
||||||
}
|
|
||||||
testsLogger = NewLogger()
|
|
||||||
|
|
||||||
captureStdout := stdoutCapture{}
|
|
||||||
captureStdout.StartCapture()
|
|
||||||
captureStderr := stderrCapture{}
|
|
||||||
captureStderr.StartCapture()
|
|
||||||
|
|
||||||
reflect.ValueOf(testsLogger).MethodByName(tt.loggerType).Call([]reflect.Value{
|
|
||||||
reflect.ValueOf(tt.args.message),
|
|
||||||
reflect.ValueOf(tt.args.extraFields),
|
|
||||||
})
|
|
||||||
|
|
||||||
stdoutOut, err := captureStdout.StopCapture()
|
|
||||||
if err != nil {
|
|
||||||
suite.T().Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
stderrOut, err := captureStderr.StopCapture()
|
|
||||||
if err != nil {
|
|
||||||
suite.T().Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if tt.stdErrExpect && !tt.stdOutExpect {
|
|
||||||
_, gotMsg, err := getResponseValues(stderrOut, "_full_message")
|
|
||||||
suite.NoError(err, "Failed in [STDERR]: "+tt.name)
|
|
||||||
suite.Equal(tt.wantMessage, gotMsg, "Failed in [STDERR]: "+tt.name)
|
|
||||||
}
|
|
||||||
if tt.stdOutExpect && !tt.stdErrExpect {
|
|
||||||
_, gotMsg, err := getResponseValues(stdoutOut, "_full_message")
|
|
||||||
suite.NoError(err, "Failed in [STDOUT]: "+tt.name)
|
|
||||||
suite.Equal(tt.wantMessage, gotMsg, "Failed in [STDOUT]: "+tt.name)
|
|
||||||
}
|
|
||||||
os.Unsetenv("LOG_LEVEL")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_getResponseValues(t *testing.T) {
|
|
||||||
type args struct {
|
|
||||||
sourceJson string
|
|
||||||
}
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
args args
|
|
||||||
wantGotLvl string
|
|
||||||
wantGotMsg string
|
|
||||||
wantErr bool
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "Test with json",
|
|
||||||
args: args{
|
|
||||||
sourceJson: `{"level": "debug", "short_message": "hello world"`,
|
|
||||||
},
|
|
||||||
wantGotLvl: "debug",
|
|
||||||
wantGotMsg: "hello world",
|
|
||||||
wantErr: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Test with json, wrong message field",
|
|
||||||
args: args{
|
|
||||||
sourceJson: `{"level": "debug", "message": "hello world"`,
|
|
||||||
},
|
|
||||||
wantGotLvl: "debug",
|
|
||||||
wantGotMsg: "",
|
|
||||||
wantErr: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
gotGotLvl, gotGotMsg, err := getResponseValues(tt.args.sourceJson, "short_message")
|
|
||||||
if (err != nil) != tt.wantErr {
|
|
||||||
t.Errorf("getResponseValues() error = %v, wantErr %v", err, tt.wantErr)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if gotGotLvl != tt.wantGotLvl {
|
|
||||||
t.Errorf("getResponseValues() gotGotLvl = %v, want %v", gotGotLvl, tt.wantGotLvl)
|
|
||||||
}
|
|
||||||
if gotGotMsg != tt.wantGotMsg {
|
|
||||||
t.Errorf("getResponseValues() gotGotMsg = %v, want %v", gotGotMsg, tt.wantGotMsg)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func getResponseValues(sourceJson string, key string) (gotLvl, gotMsg string, err error) {
|
|
||||||
gotLvl, err = jsonparser.GetString([]byte(sourceJson), "level")
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
gotMsg, err = jsonparser.GetString([]byte(sourceJson), key)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
@@ -5,10 +5,10 @@ import (
|
|||||||
"crypto/md5"
|
"crypto/md5"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
retry "github.com/avast/retry-go"
|
||||||
"github.com/lukaszraczylo/pandati"
|
"github.com/lukaszraczylo/pandati"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -52,53 +52,71 @@ func (g *GraphQL) Query(queryContent string, queryVariables interface{}, queryHe
|
|||||||
|
|
||||||
if g.Cache {
|
if g.Cache {
|
||||||
g.Log.Debug("Checking the cache for the query", map[string]interface{}{"_query": queryHash})
|
g.Log.Debug("Checking the cache for the query", map[string]interface{}{"_query": queryHash})
|
||||||
if entry, err := g.CacheStore.Get(queryHash); err == nil {
|
if entry, entryInfo, err := g.CacheStore.GetWithInfo(queryHash); err == nil {
|
||||||
g.Log.Debug("Found the query in the cache", map[string]interface{}{"_query": queryHash})
|
g.Log.Debug("Found the query in the cache", map[string]interface{}{"_query": queryHash})
|
||||||
return string(entry), nil
|
if pandati.IsZero(entryInfo.EntryStatus) {
|
||||||
|
return string(entry), nil
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
g.Log.Debug("Unable to find the query in the cache", map[string]interface{}{"_query": queryHash, "_error": err.Error()})
|
g.Log.Debug("Unable to find the query in the cache", map[string]interface{}{"_query": queryHash, "_error": err.Error()})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
httpRequest, err := http.NewRequest("POST", g.Endpoint, bytes.NewBuffer(query))
|
httpRequest, err := http.NewRequest("POST", g.Endpoint, bytes.NewBuffer(query))
|
||||||
httpRequest.Header.Add("Content-Type", "application/json")
|
// httpRequest.Header.Set("Content-Type", "application/json")
|
||||||
|
if err != nil {
|
||||||
|
g.Log.Error("Unable to create the request", map[string]interface{}{"_error": err.Error()})
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
for header, value := range queryHeaders {
|
for header, value := range queryHeaders {
|
||||||
httpRequest.Header.Add(fmt.Sprintf("%v", header), fmt.Sprintf("%v", value))
|
httpRequest.Header.Add(fmt.Sprintf("%v", header), fmt.Sprintf("%v", value))
|
||||||
}
|
}
|
||||||
|
|
||||||
httpResponse, err := g.HttpClient.Do(httpRequest)
|
var httpResponse *http.Response
|
||||||
if err != nil {
|
|
||||||
g.Log.Error("Unable to send the query", map[string]interface{}{"_error": err.Error()})
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
defer io.Copy(ioutil.Discard, httpResponse.Body)
|
|
||||||
defer httpResponse.Body.Close()
|
|
||||||
|
|
||||||
body, err = ioutil.ReadAll(httpResponse.Body)
|
err = retry.Do(
|
||||||
if err != nil {
|
func() error {
|
||||||
g.Log.Critical("Unable to read the response", map[string]interface{}{"_error": err.Error()})
|
httpResponse, err = g.HttpClient.Do(httpRequest)
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = json.Unmarshal(body, &queryResult)
|
if err != nil {
|
||||||
if err != nil {
|
g.Log.Debug("Unable to send the query RETRY", map[string]interface{}{"_error": err.Error()})
|
||||||
g.Log.Error("Unable to unmarshal the query", map[string]interface{}{"_error": err.Error()})
|
return err
|
||||||
return "", err
|
}
|
||||||
}
|
defer httpResponse.Body.Close()
|
||||||
|
|
||||||
|
if httpResponse.StatusCode <= 200 && httpResponse.StatusCode >= 204 {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err = ioutil.ReadAll(httpResponse.Body)
|
||||||
|
if err != nil {
|
||||||
|
g.Log.Debug("Unable to read the response", map[string]interface{}{"_error": err.Error()})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = json.Unmarshal(body, &queryResult)
|
||||||
|
if err != nil {
|
||||||
|
g.Log.Debug("Unable to unmarshal the query", map[string]interface{}{"_error": err.Error()})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
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), "_response_code": httpResponse.StatusCode})
|
||||||
return "", fmt.Errorf("%v", queryResult.Errors[0].Message)
|
return "", fmt.Errorf("%v", queryResult.Errors)
|
||||||
}
|
}
|
||||||
|
|
||||||
if pandati.IsZero(queryResult.Data) {
|
if pandati.IsZero(queryResult.Data) {
|
||||||
g.Log.Error("Query returned no data", map[string]interface{}{"_query": queryContent, "_variables": queryVariables})
|
g.Log.Error("Query returned no data", map[string]interface{}{"_query": queryContent, "_variables": queryVariables, "_response_code": httpResponse.StatusCode})
|
||||||
return "", errors.New("Query returned no data")
|
return "", errors.New("Query returned no data")
|
||||||
}
|
}
|
||||||
|
|
||||||
responseContent, err = json.MarshalToString(queryResult.Data)
|
responseContent, err = json.MarshalToString(queryResult.Data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
g.Log.Error("Invalid data result", map[string]interface{}{"_query": queryContent, "_variables": queryVariables, "_result": responseContent})
|
g.Log.Error("Invalid data result", map[string]interface{}{"_query": queryContent, "_variables": queryVariables, "_result": responseContent, "_response_code": httpResponse.StatusCode})
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+89
-21
@@ -2,6 +2,7 @@ package gql
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
@@ -59,6 +60,7 @@ func (suite *TestSuite) Test_GraphQL_Query() {
|
|||||||
type args struct {
|
type args struct {
|
||||||
queryContent string
|
queryContent string
|
||||||
queryVariables interface{}
|
queryVariables interface{}
|
||||||
|
queryHeaders map[string]interface{}
|
||||||
}
|
}
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
@@ -71,60 +73,85 @@ func (suite *TestSuite) Test_GraphQL_Query() {
|
|||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "Valid query, no cache",
|
name: "Valid query, no cache",
|
||||||
endpoint: "http://hasura.local/v1/graphql",
|
endpoint: "https://telegram-bot.app/v1/graphql",
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
cache_enabled: false,
|
cache_enabled: false,
|
||||||
args: args{
|
args: args{
|
||||||
queryContent: `query listUserBots {
|
queryContent: `query packages_prices {
|
||||||
tbl_bots(limit: 1) {
|
sub_group_packages_aggregate(where: {enabled: {_eq: true}}) {
|
||||||
bot_name
|
aggregate {
|
||||||
|
count
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
queryVariables: nil,
|
queryVariables: nil,
|
||||||
},
|
},
|
||||||
wantResult: `{"tbl_bots":[{"bot_name":"littleMentionBot"}]}`,
|
wantResult: `{"sub_group_packages_aggregate":{"aggregate":{"count":4}}}`,
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Valid query, no cache #2",
|
||||||
|
endpoint: "https://telegram-bot.app/v1/graphql",
|
||||||
|
isLocal: true,
|
||||||
|
cache_enabled: false,
|
||||||
|
args: args{
|
||||||
|
queryContent: `query packages_prices {
|
||||||
|
sub_group_packages_aggregate(where: {enabled: {_eq: true}}) {
|
||||||
|
aggregate {
|
||||||
|
count
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}`,
|
||||||
|
queryVariables: nil,
|
||||||
|
},
|
||||||
|
wantResult: `{"sub_group_packages_aggregate":{"aggregate":{"count":4}}}`,
|
||||||
wantErr: false,
|
wantErr: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Valid query, with cache empty",
|
name: "Valid query, with cache empty",
|
||||||
endpoint: "http://hasura.local/v1/graphql",
|
endpoint: "https://telegram-bot.app/v1/graphql",
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
cache_enabled: true,
|
cache_enabled: true,
|
||||||
args: args{
|
args: args{
|
||||||
queryContent: `query listUserBots {
|
queryContent: `query packages_prices {
|
||||||
tbl_bots(limit: 1) {
|
sub_group_packages_aggregate(where: {enabled: {_eq: true}}) {
|
||||||
bot_name
|
aggregate {
|
||||||
|
count
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
queryVariables: nil,
|
queryVariables: nil,
|
||||||
},
|
},
|
||||||
wantResult: `{"tbl_bots":[{"bot_name":"littleMentionBot"}]}`,
|
wantResult: `{"sub_group_packages_aggregate":{"aggregate":{"count":4}}}`,
|
||||||
wantErr: false,
|
wantErr: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Valid query, with cache filled",
|
name: "Valid query, with cache filled",
|
||||||
endpoint: "http://hasura.local/v1/graphql",
|
endpoint: "https://telegram-bot.app/v1/graphql",
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
cache_enabled: true,
|
cache_enabled: true,
|
||||||
args: args{
|
args: args{
|
||||||
queryContent: `query listUserBots {
|
queryContent: `query packages_prices {
|
||||||
tbl_bots(limit: 1) {
|
sub_group_packages_aggregate(where: {enabled: {_eq: true}}) {
|
||||||
bot_name
|
aggregate {
|
||||||
|
count
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
queryVariables: nil,
|
queryVariables: nil,
|
||||||
},
|
},
|
||||||
wantResult: `{"tbl_bots":[{"bot_name":"littleMentionBot"}]}`,
|
wantResult: `{"sub_group_packages_aggregate":{"aggregate":{"count":4}}}`,
|
||||||
wantErr: false,
|
wantErr: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Invalid query",
|
name: "Invalid query",
|
||||||
endpoint: "http://hasura.local/v1/graphql",
|
endpoint: "https://telegram-bot.app/v1/graphql",
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
args: args{
|
args: args{
|
||||||
queryContent: `query listUserBots {
|
queryContent: `query packages_pricez {
|
||||||
tbl_botz(limit: 1) {
|
sub_group_packages_aggregate(where: {enabled: {_eq: true}}) {
|
||||||
bot_name
|
aggregate {
|
||||||
|
count
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
queryVariables: nil,
|
queryVariables: nil,
|
||||||
@@ -132,6 +159,47 @@ func (suite *TestSuite) Test_GraphQL_Query() {
|
|||||||
wantResult: ``,
|
wantResult: ``,
|
||||||
wantErr: true,
|
wantErr: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "Valid query to https endpoint",
|
||||||
|
endpoint: "https://telegram-bot.app/v1/graphql",
|
||||||
|
isLocal: false,
|
||||||
|
args: args{
|
||||||
|
queryContent: `query packages_prices {
|
||||||
|
sub_group_packages_aggregate(where: {enabled: {_eq: true}}) {
|
||||||
|
aggregate {
|
||||||
|
count
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}`,
|
||||||
|
queryVariables: nil,
|
||||||
|
},
|
||||||
|
wantResult: `{"sub_group_packages_aggregate":{"aggregate":{"count":4}}}`,
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Valid query to github endpoint",
|
||||||
|
endpoint: "https://api.github.com/graphql",
|
||||||
|
isLocal: false,
|
||||||
|
args: args{
|
||||||
|
queryContent: `query {
|
||||||
|
repository(name: "semver-generator", owner: "lukaszraczylo", followRenames: true) {
|
||||||
|
releases(last: 2) {
|
||||||
|
nodes {
|
||||||
|
tag {
|
||||||
|
name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}`,
|
||||||
|
queryVariables: nil,
|
||||||
|
queryHeaders: map[string]interface{}{
|
||||||
|
"Authorization": "Bearer " + os.Getenv("GITHUB_TOKEN"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
wantResult: `{"repository":{"releases":{"nodes":[`,
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
suite.T().Run(tt.name, func(t *testing.T) {
|
suite.T().Run(tt.name, func(t *testing.T) {
|
||||||
@@ -140,11 +208,11 @@ func (suite *TestSuite) Test_GraphQL_Query() {
|
|||||||
// }
|
// }
|
||||||
g.Endpoint = tt.endpoint
|
g.Endpoint = tt.endpoint
|
||||||
g.Cache = tt.cache_enabled
|
g.Cache = tt.cache_enabled
|
||||||
gotResult, gotErr := g.Query(tt.args.queryContent, tt.args.queryVariables, nil)
|
gotResult, gotErr := g.Query(tt.args.queryContent, tt.args.queryVariables, tt.args.queryHeaders)
|
||||||
if tt.wantErr {
|
if tt.wantErr {
|
||||||
assert.Error(t, gotErr)
|
assert.Error(t, gotErr)
|
||||||
}
|
}
|
||||||
assert.Equal(t, tt.wantResult, gotResult)
|
assert.Contains(t, gotResult, tt.wantResult)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
fmt.Println(g.CacheStore.Capacity())
|
fmt.Println(g.CacheStore.Capacity())
|
||||||
|
|||||||
Reference in New Issue
Block a user