-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
104 lines (84 loc) · 1.98 KB
/
Copy pathclient.go
File metadata and controls
104 lines (84 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
// TODO: Create Stripe style sdk
/*type API struct {
Platforms *platform.Client
}*/
type AdminClient struct {
Endpoint string
AdminSecret string
}
type GraphQLVariables map[string]interface{}
type GraphQLErrorExtensions struct {
Code string `json:"code"`
Path string `json:"path"`
}
type GraphQLError struct {
Message string `json:"message"`
Extensions GraphQLErrorExtensions `json:"extensions"`
}
type GraphQLErrors []GraphQLError
func (errs GraphQLErrors) Error() string {
var sb strings.Builder
sb.WriteString("ERROR\n")
for _, err := range errs {
sb.WriteString(
fmt.Sprintf("%s ON %s -> %s", err.Extensions.Code, err.Extensions.Path, err.Message),
)
}
return sb.String()
}
type GraphQLResult struct {
Data json.RawMessage `json:"data"`
Errors GraphQLErrors `json:"errors"`
}
func (c *AdminClient) Request(
query string,
variables map[string]interface{},
) (*GraphQLResult, error) {
body, err := json.Marshal(map[string]interface{}{
"query": query,
"variables": variables,
})
if err != nil {
return nil, err
}
request, err := http.NewRequest(
"POST",
c.Endpoint,
bytes.NewBuffer(body),
)
request.Header.Set("Content-Type", "application/json")
request.Header.Set("X-Hasura-Admin-Secret", c.AdminSecret)
// bytes, err := httputil.DumpRequest(request, true)
// fmt.Printf("%s\n", string(bytes))
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err = ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
var result GraphQLResult
err = json.Unmarshal(body, &result)
if err != nil {
return nil, err
}
if result.Errors == nil {
return &result, nil
} else if len(result.Errors) > 0 {
return nil, result.Errors
}
return nil, errors.New("Unknown error occured")
}