/
handler.go
159 lines (139 loc) · 4.35 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
package apollo
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
graphql "github.com/neelance/graphql-go"
)
const (
ContentTypeJSON = "application/json"
ContentTypeGraphQL = "application/graphql"
ContentTypeFormURLEncoded = "application/x-www-form-urlencoded"
)
type Handler struct {
Schema *graphql.Schema
Pretty bool
}
type RequestOptions struct {
Query string `json:"query" url:"query"`
Variables map[string]interface{} `json:"variables" url:"variables"`
OperationName string `json:"operationName" url:"operationName"`
}
// a workaround for getting`variables` as a JSON string
type requestOptionsCompatibility struct {
Query string `json:"query" url:"query"`
Variables string `json:"variables" url:"variables"`
OperationName string `json:"operationName" url:"operationName"`
}
func getFromForm(values url.Values) *RequestOptions {
query := values.Get("query")
if query != "" {
// get variables map
var variables map[string]interface{}
variablesStr := values.Get("variables")
json.Unmarshal([]byte(variablesStr), &variables)
return &RequestOptions{
Query: query,
Variables: variables,
OperationName: values.Get("operationName"),
}
}
return nil
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var output interface{}
// TODO: improve Content-Type handling
contentTypeStr := r.Header.Get("Content-Type")
contentTypeTokens := strings.Split(contentTypeStr, ";")
contentType := contentTypeTokens[0]
switch contentType {
case ContentTypeFormURLEncoded:
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
query := getFromForm(r.PostForm)
if query == nil {
http.Error(w, "Could not parse graphql params from form.", http.StatusInternalServerError)
return
}
output = h.Schema.Exec(r.Context(), query.Query, query.OperationName, query.Variables)
case ContentTypeGraphQL:
body, err := ioutil.ReadAll(r.Body)
if err == nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
output = h.Schema.Exec(r.Context(), string(body), "", make(map[string]interface{}))
case ContentTypeJSON:
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
requestOptions := resolveJSON(body)
switch opts := requestOptions.(type) {
case *RequestOptions:
output = h.Schema.Exec(r.Context(), opts.Query, opts.OperationName, opts.Variables)
case []*RequestOptions:
var results []*graphql.Response
for i := range opts {
results = append(results, h.Schema.Exec(r.Context(), opts[i].Query, opts[i].OperationName, opts[i].Variables))
}
output = results
default:
log.Printf("bad type: %T", opts)
http.Error(w, "unrecognized RequestOptions type", http.StatusBadRequest)
return
}
default:
http.Error(w, "unrecognized content-type header: `"+contentType+"`", http.StatusBadRequest)
return
}
var responseJSON []byte
var err error
if h.Pretty {
responseJSON, err = json.MarshalIndent(output, "", " ")
} else {
responseJSON, err = json.Marshal(output)
}
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.WriteHeader(http.StatusOK)
w.Write(responseJSON)
}
func resolveJSON(body []byte) interface{} {
if bytes.HasPrefix(body, []byte("[")) {
var queries []*RequestOptions
err := json.Unmarshal(body, &queries)
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 optionsCompatible []*requestOptionsCompatibility
json.Unmarshal(body, &optionsCompatible)
for i := range optionsCompatible {
json.Unmarshal([]byte(optionsCompatible[i].Variables), &queries[i].Variables)
}
return queries
}
return queries
}
var query RequestOptions
err := json.Unmarshal(body, &query)
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 optionsCompatible requestOptionsCompatibility
json.Unmarshal(body, &optionsCompatible)
json.Unmarshal([]byte(optionsCompatible.Variables), &query.Variables)
return &query
}
return &query
}