forked from lablabs/cloudflare-exporter
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgraphql.go
More file actions
105 lines (86 loc) · 2.23 KB
/
graphql.go
File metadata and controls
105 lines (86 loc) · 2.23 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
105
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
const (
cfGraphQLEndpoint = "https://api.cloudflare.com/client/v4/graphql/"
gqlQueryLimit = 9999
cfgraphqlreqlimit = 10 // 10 is the maximum amount of zones you can request at once
)
type GraphQL struct {
httpClient *http.Client
headers http.Header
reqTimeout time.Duration
}
type GraphQLRequest struct {
Query string `json:"query"`
Vars map[string]any `json:"variables"`
}
type GraphQLResponse struct {
Data any `json:"data"`
Errors []*GraphQLError `json:"errors"`
}
type GraphQLError struct {
Message string `json:"message"`
}
func (e *GraphQLError) Error() string {
return e.Message
}
var _ error = (*GraphQLError)(nil)
func NewGraphQLClient(headers http.Header, reqTimeout time.Duration) *GraphQL {
return &GraphQL{
httpClient: http.DefaultClient,
headers: headers,
reqTimeout: reqTimeout,
}
}
func (g *GraphQL) Run(ctx context.Context, gReq *GraphQLRequest, repStruct any) error {
if err := context.Cause(ctx); err != nil {
return err
}
ctx, cancel := context.WithTimeout(ctx, g.reqTimeout)
defer cancel()
var body bytes.Buffer
if err := json.NewEncoder(&body).Encode(gReq); err != nil {
return fmt.Errorf("failed to marshal query body: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, cfGraphQLEndpoint, &body)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Accept", "application/json; charset=utf-8")
for k, vs := range g.headers {
for _, v := range vs {
req.Header.Add(k, v)
}
}
rep, err := g.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to execute request: %w", err)
}
defer rep.Body.Close()
gRep := GraphQLResponse{Data: repStruct}
if err := json.NewDecoder(rep.Body).Decode(&gRep); err != nil {
return fmt.Errorf("failed to decode response: %w", err)
}
errs := make([]error, len(gRep.Errors))
for _, e := range gRep.Errors {
errs = append(errs, e)
}
return errors.Join(errs...)
}
func NewGraphQLRequest(query string) *GraphQLRequest {
return &GraphQLRequest{
Query: query,
Vars: map[string]any{},
}
}
func (r *GraphQLRequest) Var(key string, val any) {
r.Vars[key] = val
}