-
Notifications
You must be signed in to change notification settings - Fork 0
/
translator.go
278 lines (224 loc) · 6.69 KB
/
translator.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package grapher
import (
"fmt"
"github.com/graphql-go/graphql"
"github.com/reaganiwadha/grapher/scalars"
"reflect"
"strings"
)
// TranslationMap is a map that stores the graphql.Output according to it's type
type TranslationMap map[string]graphql.Output
var primitiveTranslationTable = TranslationMap{
"int": graphql.Int,
"int8": graphql.Int,
"int16": graphql.Int,
"int32": graphql.Int,
"int64": graphql.Int,
"uint": graphql.Int,
"uint8": graphql.Int,
"uint16": graphql.Int,
"uint32": graphql.Int,
"uint64": graphql.Int,
"float32": graphql.Float,
"float64": graphql.Float,
"string": graphql.String,
"bool": graphql.Boolean,
"time.Time": graphql.DateTime,
}
// TranslatorConfig Stores the configuration of the graphql object builder
type TranslatorConfig struct {
// PredefinedTranslation ignores whether it's a pointer or not, beware!
PredefinedTranslation TranslationMap
}
type translator struct {
outputObjTable TranslationMap
outputInputObjTable TranslationMap
predefinedTranslation TranslationMap
}
func getNamingByStructField(field reflect.StructField) string {
jsonTag := field.Tag.Get("json")
if jsonTag != "" {
idx := strings.Index(jsonTag, ",")
if idx == -1 {
return jsonTag
}
return jsonTag[:idx]
}
return field.Name
}
// Translator purpose is to provide an easy way of translating various types into graphql types
type Translator interface {
Translate(t interface{}) (ret graphql.Output, err error)
TranslateInput(t interface{}) (ret *graphql.InputObject, err error)
TranslateArgs(t interface{}) (ret graphql.FieldConfigArgument, err error)
MustTranslate(t interface{}) graphql.Output
MustTranslateInput(t interface{}) *graphql.InputObject
MustTranslateArgs(t interface{}) (ret graphql.FieldConfigArgument)
}
// NewTranslator returns a new translator
// It also stores already translated graphql.Object/graphql.InputObject to eliminate duplicates
func NewTranslator(args ...*TranslatorConfig) Translator {
t := translator{
outputObjTable: TranslationMap{},
outputInputObjTable: TranslationMap{},
}
if len(args) != 0 {
arg := args[0]
if arg.PredefinedTranslation != nil {
t.predefinedTranslation = arg.PredefinedTranslation
}
}
return &t
}
func sanitizeGenericTypeString(s string) (result string) {
begin := s[0:strings.Index(s, "[")]
generics := strings.Split(s[strings.Index(s, "[")+1:strings.Index(s, "]")], ",")
processedGenerics := []string{}
if strings.Contains(begin, ".") {
begin = begin[strings.LastIndex(begin, ".")+1:]
}
for _, v := range generics {
g := v[strings.LastIndex(v, "/")+1:]
g = g[strings.LastIndex(g, ".")+1:]
processedGenerics = append(processedGenerics, g)
}
result = begin
for _, v := range processedGenerics {
result = fmt.Sprintf("%v_%v", result, v)
}
return
}
func (g *translator) translateOutputRefType(t reflect.Type, inputObject bool) (ret graphql.Output, err error) {
isPtr := false
isArr := false
for t.Kind() == reflect.Ptr {
t = t.Elem()
isPtr = true
}
if t.Kind() == reflect.Slice || t.Kind() == reflect.Array {
t = t.Elem()
isArr = true
}
tName := t.String()
if predefined, ok := g.predefinedTranslation[tName]; ok {
ret = predefined
return
} else if cached, ok := g.outputObjTable[tName]; ok && !inputObject {
ret = cached
} else if cached, ok := g.outputInputObjTable[tName]; ok && inputObject {
ret = cached
} else if prim, ok := primitiveTranslationTable[tName]; ok {
ret = prim
} else if t.Kind() == reflect.Map {
ret = scalars.ScalarJSON
} else if t.Kind() == reflect.Struct {
fields := graphql.Fields{}
inputFields := graphql.InputObjectConfigFieldMap{}
for i := 0; i < t.NumField(); i++ {
fieldT := t.Field(i).Type
fieldDesc := t.Field(i).Tag.Get("grapher_d")
fieldOut, _ := g.translateOutputRefType(fieldT, inputObject)
if inputObject {
inputFields[getNamingByStructField(t.Field(i))] = &graphql.InputObjectFieldConfig{
Type: fieldOut,
Description: fieldDesc,
}
} else {
fields[getNamingByStructField(t.Field(i))] = &graphql.Field{
Type: fieldOut,
Description: fieldDesc,
}
}
}
inputObjName := t.Name()
if strings.ContainsAny(inputObjName, "[") {
inputObjName = sanitizeGenericTypeString(inputObjName)
}
if inputObject {
ret = graphql.NewInputObject(graphql.InputObjectConfig{
Name: inputObjName,
Fields: inputFields,
})
g.outputInputObjTable[t.String()] = ret
} else {
ret = graphql.NewObject(graphql.ObjectConfig{
Name: inputObjName,
Fields: fields,
})
g.outputObjTable[t.String()] = ret
}
}
if !isPtr {
ret = graphql.NewNonNull(ret)
}
if isArr {
ret = graphql.NewList(ret)
}
return
}
// Translate translates the type into a *graphql.Object
func (g *translator) Translate(t interface{}) (ret graphql.Output, err error) {
v := reflect.TypeOf(t)
return g.translateOutputRefType(v, false)
}
// MustTranslate calls Translate, but will panic on error
func (g *translator) MustTranslate(t interface{}) graphql.Output {
ret, _ := g.Translate(t)
// No errors as of now
//if err != nil {
// panic(err)
//}
return ret
}
func assertStruct(v reflect.Type) (structType reflect.Type, err error) {
if v.Kind() == reflect.Pointer {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return nil, fmt.Errorf("grapher: not a struct type")
}
return v, nil
}
// TranslateInput translates a struct into a *graphql.InputObject
func (g *translator) TranslateInput(t interface{}) (ret *graphql.InputObject, err error) {
v := reflect.TypeOf(t)
if _, err = assertStruct(v); err != nil {
return
}
out, err := g.translateOutputRefType(v, true)
return out.(*graphql.InputObject), err
}
// MustTranslateInput calls TranslateInputObject, but will panic on error
func (g *translator) MustTranslateInput(t interface{}) *graphql.InputObject {
ret, err := g.TranslateInput(t)
if err != nil {
panic(err)
}
return ret
}
// TranslateArgs translates a struct into a graphql.FieldConfigArgument
func (g *translator) TranslateArgs(t interface{}) (ret graphql.FieldConfigArgument, err error) {
structType, err := assertStruct(reflect.TypeOf(t))
if err != nil {
return
}
ret = graphql.FieldConfigArgument{}
for i := 0; i < structType.NumField(); i++ {
field, _ := g.translateOutputRefType(structType.Field(i).Type, true)
//if fieldErr != nil{
// return nil, fieldErr
//}
ret[getNamingByStructField(structType.Field(i))] = &graphql.ArgumentConfig{
Type: field,
}
}
return
}
// MustTranslateArgs calls TranslateArgs, but will panic on error
func (g translator) MustTranslateArgs(t interface{}) (ret graphql.FieldConfigArgument) {
ret, err := g.TranslateArgs(t)
if err != nil {
panic(err)
}
return
}