forked from shurcooL/graphql
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgraphql.go
177 lines (159 loc) · 5.02 KB
/
graphql.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package graphql
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/shurcooL/graphql/internal/jsonutil"
)
// Client is a GraphQL client.
type Client struct {
url string // GraphQL server URL.
httpClient *http.Client // Non-nil.
}
// NewClient creates a GraphQL client targeting the specified GraphQL server URL.
// If httpClient is nil, then http.DefaultClient is used.
func NewClient(url string, httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
return &Client{
url: url,
httpClient: httpClient,
}
}
// Query executes a single GraphQL query request,
// with a query derived from q, populating the response into it.
// q should be a pointer to struct that corresponds to the GraphQL schema.
func (c *Client) Query(ctx context.Context, q any, variables map[string]any) error {
return c.do(ctx, queryOperation, q, variables, nil)
}
// QueryWithExtensions executes a single GraphQL query request,
// with a query derived from q, populating the response into it.
// q should be a pointer to struct that corresponds to the GraphQL schema.
// Additionally, this will capture the extensions from the response.
// extensions should be a pointer that corresponds to the extensions schema.
func (c *Client) QueryWithExtensions(ctx context.Context, q interface{}, variables map[string]interface{}, extensions interface{}) error {
return c.do(ctx, queryOperation, q, variables, extensions)
}
// Mutate executes a single GraphQL mutation request,
// with a mutation derived from m, populating the response into it.
// m should be a pointer to struct that corresponds to the GraphQL schema.
func (c *Client) Mutate(ctx context.Context, m any, variables map[string]any) error {
return c.do(ctx, mutationOperation, m, variables, nil)
}
// MutateWithExtensions executes a single GraphQL mutation request,
// with a mutation derived from m, populating the response into it.
// m should be a pointer to struct that corresponds to the GraphQL schema.
// Additionally, this will capture the extensions from the response.
// extensions should be a pointer that corresponds to the extensions schema.
func (c *Client) MutateWithExtensions(ctx context.Context, m interface{}, variables map[string]interface{}, extensions interface{}) error {
return c.do(ctx, mutationOperation, m, variables, extensions)
}
// do executes a single GraphQL operation.
func (c *Client) do(ctx context.Context, op operationType, v any, variables map[string]any, extensions any) error {
var query string
switch op {
case queryOperation:
query = constructQuery(v, variables)
case mutationOperation:
query = constructMutation(v, variables)
}
in := struct {
Query string `json:"query"`
Variables map[string]any `json:"variables,omitempty"`
}{
Query: query,
Variables: variables,
}
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(in)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, &buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return ErrResponseStatusNotOK{
body: resp.Body,
statusCode: resp.StatusCode,
status: resp.Status,
}
}
var out struct {
Data *json.RawMessage
Errors errors
Extensions *json.RawMessage
}
err = json.NewDecoder(resp.Body).Decode(&out)
if err != nil {
// TODO: Consider including response body in returned error, if deemed helpful.
return err
}
if out.Data != nil {
err := jsonutil.UnmarshalGraphQL(*out.Data, v)
if err != nil {
// TODO: Consider including response body in returned error, if deemed helpful.
return err
}
}
if extensions != nil && out.Extensions != nil {
err := jsonutil.UnmarshalGraphQL(*out.Extensions, extensions)
if err != nil {
// TODO: Consider including response body in returned error, if deemed helpful.
return err
}
}
if len(out.Errors) > 0 {
return out.Errors
}
return nil
}
// errors represents the "errors" array in a response from a GraphQL server.
// If returned via error interface, the slice is expected to contain at least 1 element.
//
// Specification: https://spec.graphql.org/October2021/#sec-Errors.
type errors []struct {
Message string
Locations []struct {
Line int
Column int
}
}
// Error implements error interface.
func (e errors) Error() string {
return e[0].Message
}
type ErrResponseStatusNotOK struct {
body io.ReadCloser
status string
statusCode int
}
func (e ErrResponseStatusNotOK) Error() string {
return fmt.Sprintf("non-200 OK status code: %s", e.status)
}
func (e ErrResponseStatusNotOK) Body() io.ReadCloser {
return e.body
}
func (e ErrResponseStatusNotOK) Status() string {
return e.status
}
func (e ErrResponseStatusNotOK) StatusCode() int {
return e.statusCode
}
type operationType uint8
const (
queryOperation operationType = iota
mutationOperation
// subscriptionOperation // Unused.
)