Fix setting up the URL.

This commit is contained in:
2021-04-03 01:07:41 +01:00
parent 5b5d0979b1
commit 60d5a991a0
2 changed files with 45 additions and 6 deletions
+8 -5
View File
@@ -11,7 +11,6 @@ import (
"fmt"
"os"
"github.com/lukaszraczylo/zero"
"github.com/tidwall/gjson"
"github.com/valyala/fasthttp"
)
@@ -19,16 +18,19 @@ import (
// Endpoint of your GraphQL server to query
// this variable can be overwritten by setting env variable, for example:
// GRAPHQL_ENDPOINT=http://hasura.local/v1/graphql
var GraphQLUrl = "http://127.0.0.1:9090/v1/graphql"
var GraphQLUrl string
type requestBase struct {
Query string `json:"query"`
Variables interface{} `json:"variables"`
}
func init() {
if !zero.IsZero(os.Getenv("GRAPHQL_ENDPOINT")) {
GraphQLUrl = os.Getenv("GRAPHQL_ENDPOINT")
func prepare() {
value, present := os.LookupEnv("GRAPHQL_ENDPOINT")
if present {
GraphQLUrl = value
} else {
GraphQLUrl = "http://127.0.0.1:9090/v1/graphql"
}
}
@@ -56,6 +58,7 @@ func queryBuilder(data string, variables interface{}) ([]byte, error) {
// Variables and Headers are maps of strings ( see the example )
// Function returns whatever specified query returns and/or error.
func Query(query string, variables interface{}, headers map[string]interface{}) (string, error) {
prepare()
var err error
readyQuery, err := queryBuilder(query, variables)
if err != nil {
+37 -1
View File
@@ -2,6 +2,7 @@ package gql
import (
"fmt"
"os"
"testing"
"github.com/stretchr/testify/assert"
@@ -37,8 +38,8 @@ func Test_queryBuilder(t *testing.T) {
want: `{"query":"query checkifUserIsAdmin($UserID: bigint, $GroupID: bigint) { tbl_user_group_admins(where: {is_admin: {_eq: \"1\"}, user_id: {_eq: $UserID}, group_id: {_eq: $GroupID}}) { id is_admin } }","variables":{"GroupID":11007,"UserID":37}}`,
},
}
assert := assert.New(t)
for _, tt := range tests {
assert := assert.New(t)
t.Run(tt.name, func(t *testing.T) {
gets, err := queryBuilder(tt.args.data, tt.args.variables)
assert.Equal(tt.want, string(gets), "Unexpected query output in test: "+tt.name)
@@ -94,3 +95,38 @@ func ExampleQuery() {
}
fmt.Println(result)
}
func Test_initialize(t *testing.T) {
tests := []struct {
name string
expected string
env_endpoint string
}{
{
name: "Setting env variable for endpoint",
env_endpoint: "hasura.local/v1/graphql",
expected: "hasura.local/v1/graphql",
},
{
name: "Setting default endpoint",
env_endpoint: "",
expected: "http://127.0.0.1:9090/v1/graphql",
},
}
assert := assert.New(t)
backupEnv, present := os.LookupEnv("GRAPHQL_ENDPOINT")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.env_endpoint != "" {
os.Setenv("GRAPHQL_ENDPOINT", tt.env_endpoint)
}
t.Log(tt.env_endpoint, os.Getenv("GRAPHQL_ENDPOINT"))
prepare()
assert.Equal(tt.expected, GraphQLUrl, "Unexpected value of env variable: "+tt.name)
os.Unsetenv("GRAPHQL_ENDPOINT")
})
}
if present {
os.Setenv("GRAPHQL_ENDPOINT", backupEnv)
}
}