-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
111 lines (97 loc) · 2.56 KB
/
client.go
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
105
106
107
108
109
110
111
package fuel
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type Client struct {
endpoint string
httpClient http.Client
logger Logger
}
func NewClient(endpoint string) *Client {
return &Client{endpoint: endpoint}
}
func NewClientWithLogger(endpoint string, logger Logger) *Client {
return &Client{endpoint: endpoint, logger: logger}
}
type QueryErrorLocation struct {
Line int `json:"line"`
Column int `json:"column"`
}
func (loc QueryErrorLocation) String() string {
return fmt.Sprintf("(line:%d,column:%d)", loc.Line, loc.Column)
}
type QueryError struct {
Message string `json:"message"`
Locations []QueryErrorLocation `json:"locations"`
}
func (e QueryError) String() string {
var buf bytes.Buffer
for i, loc := range e.Locations {
if i > 0 {
buf.WriteRune(',')
}
buf.WriteString(loc.String())
}
buf.WriteString(": ")
buf.WriteString(e.Message)
return buf.String()
}
type QueryErrors []QueryError
func (e QueryErrors) Error() string {
var buf bytes.Buffer
for i, ei := range e {
if i > 0 {
buf.WriteRune('\n')
}
buf.WriteString(ei.String())
}
return fmt.Sprintf("execute query failed: %s", buf.String())
}
func ExecuteQuery[DATA any](ctx context.Context, cli *Client, query string) (data DATA, err error) {
if cli.logger != nil {
cli.logger.Infof("execute query: %s", query)
}
start := time.Now()
var reqBody bytes.Buffer
if err = json.NewEncoder(&reqBody).Encode(map[string]any{"query": query}); err != nil {
return data, fmt.Errorf("build request failed: %w", err)
}
var req *http.Request
req, err = http.NewRequestWithContext(ctx, "POST", cli.endpoint, &reqBody)
req.Header.Add("content-type", "application/json")
req.Header.Add("Accept", "application/json")
if err != nil {
return data, fmt.Errorf("build request failed: %w", err)
}
var resp *http.Response
resp, err = cli.httpClient.Do(req)
if err != nil {
return data, fmt.Errorf("send request failed: %w", err)
}
defer resp.Body.Close()
var respBody []byte
respBody, err = io.ReadAll(resp.Body)
if err != nil {
return data, fmt.Errorf("read response body failed: %w", err)
}
if cli.logger != nil {
cli.logger.Infof("query result(len: %d, used: %s): %s", len(respBody), time.Since(start), string(respBody))
}
var result struct {
Data DATA `json:"data"`
Errors QueryErrors `json:"errors"`
}
if err = json.Unmarshal(respBody, &result); err != nil {
return data, fmt.Errorf("parse response body failed: %w", err)
}
if len(result.Errors) > 0 {
return data, result.Errors
}
return result.Data, nil
}