forked from graphql-go/handler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
236 lines (199 loc) · 5.97 KB
/
handler.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package handler
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/graphql-go/graphql"
"context"
"github.com/graphql-go/graphql/gqlerrors"
)
const (
ContentTypeJSON = "application/json"
ContentTypeGraphQL = "application/graphql"
ContentTypeFormURLEncoded = "application/x-www-form-urlencoded"
)
type ResultCallbackFn func(ctx context.Context, params *graphql.Params, result *graphql.Result, responseBody []byte)
type Handler struct {
Schema *graphql.Schema
pretty bool
graphiql bool
playground bool
rootObjectFn RootObjectFn
resultCallbackFn ResultCallbackFn
formatErrorFn func(err error) gqlerrors.FormattedError
}
type RequestOptions struct {
Query string `json:"query" url:"query" schema:"query"`
Variables map[string]interface{} `json:"variables" url:"variables" schema:"variables"`
OperationName string `json:"operationName" url:"operationName" schema:"operationName"`
}
// a workaround for getting`variables` as a JSON string
type requestOptionsCompatibility struct {
Query string `json:"query" url:"query" schema:"query"`
Variables string `json:"variables" url:"variables" schema:"variables"`
OperationName string `json:"operationName" url:"operationName" schema:"operationName"`
}
func getFromForm(values url.Values) *RequestOptions {
query := values.Get("query")
if query != "" {
// get variables map
variables := make(map[string]interface{}, len(values))
variablesStr := values.Get("variables")
json.Unmarshal([]byte(variablesStr), &variables)
return &RequestOptions{
Query: query,
Variables: variables,
OperationName: values.Get("operationName"),
}
}
return nil
}
// RequestOptions Parses a http.Request into GraphQL request options struct
func NewRequestOptions(r *http.Request) *RequestOptions {
if reqOpt := getFromForm(r.URL.Query()); reqOpt != nil {
return reqOpt
}
if r.Method != http.MethodPost {
return &RequestOptions{}
}
if r.Body == nil {
return &RequestOptions{}
}
// TODO: improve Content-Type handling
contentTypeStr := r.Header.Get("Content-Type")
contentTypeTokens := strings.Split(contentTypeStr, ";")
contentType := contentTypeTokens[0]
switch contentType {
case ContentTypeGraphQL:
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return &RequestOptions{}
}
return &RequestOptions{
Query: string(body),
}
case ContentTypeFormURLEncoded:
if err := r.ParseForm(); err != nil {
return &RequestOptions{}
}
if reqOpt := getFromForm(r.PostForm); reqOpt != nil {
return reqOpt
}
return &RequestOptions{}
case ContentTypeJSON:
fallthrough
default:
var opts RequestOptions
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return &opts
}
err = json.Unmarshal(body, &opts)
if err != nil {
// Probably `variables` was sent as a string instead of an object.
// So, we try to be polite and try to parse that as a JSON string
var optsCompatible requestOptionsCompatibility
json.Unmarshal(body, &optsCompatible)
json.Unmarshal([]byte(optsCompatible.Variables), &opts.Variables)
}
return &opts
}
}
// ContextHandler provides an entrypoint into executing graphQL queries with a
// user-provided context.
func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
// get query
opts := NewRequestOptions(r)
// execute graphql query
params := graphql.Params{
Schema: *h.Schema,
RequestString: opts.Query,
VariableValues: opts.Variables,
OperationName: opts.OperationName,
Context: ctx,
}
if h.rootObjectFn != nil {
params.RootObject = h.rootObjectFn(ctx, r)
}
result := graphql.Do(params)
if formatErrorFn := h.formatErrorFn; formatErrorFn != nil && len(result.Errors) > 0 {
formatted := make([]gqlerrors.FormattedError, len(result.Errors))
for i, formattedError := range result.Errors {
formatted[i] = formatErrorFn(formattedError.OriginalError())
}
result.Errors = formatted
}
if h.graphiql {
acceptHeader := r.Header.Get("Accept")
_, raw := r.URL.Query()["raw"]
if !raw && !strings.Contains(acceptHeader, "application/json") && strings.Contains(acceptHeader, "text/html") {
renderGraphiQL(w, params)
return
}
}
if h.playground {
acceptHeader := r.Header.Get("Accept")
_, raw := r.URL.Query()["raw"]
if !raw && !strings.Contains(acceptHeader, "application/json") && strings.Contains(acceptHeader, "text/html") {
renderPlayground(w, r)
return
}
}
// use proper JSON Header
w.Header().Add("Content-Type", "application/json; charset=utf-8")
var buff []byte
if h.pretty {
w.WriteHeader(http.StatusOK)
buff, _ = json.MarshalIndent(result, "", "\t")
w.Write(buff)
} else {
w.WriteHeader(http.StatusOK)
buff, _ = json.Marshal(result)
w.Write(buff)
}
if h.resultCallbackFn != nil {
h.resultCallbackFn(ctx, ¶ms, result, buff)
}
}
// ServeHTTP provides an entrypoint into executing graphQL queries.
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.ContextHandler(r.Context(), w, r)
}
// RootObjectFn allows a user to generate a RootObject per request
type RootObjectFn func(ctx context.Context, r *http.Request) map[string]interface{}
type Config struct {
Schema *graphql.Schema
Pretty bool
GraphiQL bool
Playground bool
RootObjectFn RootObjectFn
ResultCallbackFn ResultCallbackFn
FormatErrorFn func(err error) gqlerrors.FormattedError
}
func NewConfig() *Config {
return &Config{
Schema: nil,
Pretty: true,
GraphiQL: true,
Playground: false,
}
}
func New(p *Config) *Handler {
if p == nil {
p = NewConfig()
}
if p.Schema == nil {
panic("undefined GraphQL schema")
}
return &Handler{
Schema: p.Schema,
pretty: p.Pretty,
graphiql: p.GraphiQL,
playground: p.Playground,
rootObjectFn: p.RootObjectFn,
resultCallbackFn: p.ResultCallbackFn,
formatErrorFn: p.FormatErrorFn,
}
}