-
Notifications
You must be signed in to change notification settings - Fork 13
/
query.go
117 lines (106 loc) · 2.35 KB
/
query.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
package graphqlparser
import (
"bytes"
"encoding/json"
"io"
"reflect"
"sort"
"strings"
)
func constructQuery(v interface{}, variables map[string]interface{}) string {
query := query(v)
if len(variables) > 0 {
return "query(" + queryArguments(variables) + ")" + query
}
return query
}
func constructMutation(v interface{}, variables map[string]interface{}) string {
query := query(v)
if len(variables) > 0 {
return "mutation(" + queryArguments(variables) + ")" + query
}
return "mutation" + query
}
func queryArguments(variables map[string]interface{}) string {
keys := make([]string, 0, len(variables))
for k := range variables {
keys = append(keys, k)
}
sort.Strings(keys)
var buf bytes.Buffer
for _, k := range keys {
// nolint
io.WriteString(&buf, "$")
// nolint
io.WriteString(&buf, k)
// nolint
io.WriteString(&buf, ":")
writeArgumentType(&buf, reflect.TypeOf(variables[k]), true)
}
return buf.String()
}
func writeArgumentType(w io.Writer, t reflect.Type, value bool) {
if t.Kind() == reflect.Ptr {
writeArgumentType(w, t.Elem(), false)
return
}
switch t.Kind() {
case reflect.Slice, reflect.Array:
// nolint
io.WriteString(w, "[")
writeArgumentType(w, t.Elem(), true)
// nolint
io.WriteString(w, "]")
default:
// nolint
io.WriteString(w, strings.Title(t.Name()))
}
if value {
// nolint
io.WriteString(w, "!")
}
}
func query(v interface{}) string {
var buf bytes.Buffer
writeQuery(&buf, reflect.TypeOf(v), false)
return buf.String()
}
func writeQuery(w io.Writer, t reflect.Type, inline bool) {
switch t.Kind() {
case reflect.Ptr, reflect.Slice:
writeQuery(w, t.Elem(), false)
case reflect.Struct:
if reflect.PtrTo(t).Implements(jsonUnmarshaler) {
return
}
if !inline {
// nolint
io.WriteString(w, "{")
}
for i := 0; i < t.NumField(); i++ {
if i != 0 {
// nolint
io.WriteString(w, ",")
}
f := t.Field(i)
value, ok := f.Tag.Lookup("graphql")
inlineField := f.Anonymous && !ok
if !inlineField {
if ok {
// nolint
io.WriteString(w, value)
} else {
// nolint
//io.WriteString(w, ident.ParseMixedCaps(f.Name).ToLowerCamelCase())
io.WriteString(w, f.Name)
}
}
writeQuery(w, f.Type, inlineField)
}
if !inline {
// nolint
io.WriteString(w, "}")
}
}
}
var jsonUnmarshaler = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()