-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgraphql.go
102 lines (93 loc) · 2.45 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
package hyper
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/graphql-go/graphql"
"github.com/vaniila/hyper/router"
)
// GQLQueries parameters
var GQLQueries = []router.Param{
Query("query").
Format(Text).
Require(false),
Query("variables").
Format(Text).
Require(false),
}
// GQLBodies parameters
var GQLBodies = []router.Param{
Body("query").
Format(Text).
Require(false),
Body("variables").
Format(Text).
Require(false),
Body("file").
Format(File).
Require(false),
}
// Payload struct
type Payload struct {
RawQuery string `json:"-"`
RawVariables string `json:"-"`
ParsedQuery string `json:"query"`
ParsedVariables map[string]interface{} `json:"variables"`
}
// Parse to read raw query and variables
func (v *Payload) Parse() {
v.ParsedQuery = v.RawQuery
v.ParsedVariables = make(map[string]interface{})
json.Unmarshal([]byte(v.RawVariables), &v.ParsedVariables)
}
// GraphQL handles graphql
func GraphQL(schema graphql.Schema) router.HandlerFunc {
return func(c router.Context) {
var payload = new(Payload)
switch c.Req().Method {
case "PUT", "POST", "PATCH", "CONNECT":
switch {
case c.MustBody("query").Has() || c.MustBody("variables").Has():
payload.RawQuery = c.MustBody("query").String()
payload.RawVariables = c.MustBody("variables").String()
payload.Parse()
default:
b, _ := ioutil.ReadAll(c.Req().Body)
if err := json.Unmarshal(b, &payload); err != nil {
payload.ParsedQuery = string(b[:])
}
}
default:
switch {
case c.MustQuery("query").Has() || c.MustQuery("variables").Has():
payload.RawQuery = c.MustQuery("query").String()
payload.RawVariables = c.MustQuery("variables").String()
payload.Parse()
default:
r := c.Req().URL.RawQuery
b := []byte(r)
if err := json.Unmarshal(b, &payload); err != nil {
payload.ParsedQuery = r
}
}
}
span := c.StartSpan("HTTP GraphQL Execution")
span.LogKV("graphql-query", payload.ParsedQuery)
for k, v := range payload.ParsedVariables {
span.LogKV(fmt.Sprintf("graphql-variable:%s", k), v)
}
defer span.Finish()
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: payload.ParsedQuery,
VariableValues: payload.ParsedVariables,
Context: c.Context(),
})
if result.HasErrors() {
c.Status(http.StatusForbidden)
}
span.LogKV("graphql-result", result)
c.Json(result)
}
}