forked from lab259/go-graphql-struct
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtypes.go
More file actions
72 lines (63 loc) · 2.06 KB
/
Copy pathtypes.go
File metadata and controls
72 lines (63 loc) · 2.06 KB
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
package gqlstruct
import (
"github.com/graphql-go/graphql"
"reflect"
"time"
)
// GraphqlTyped is the interface implemented by types that will provide a
// special `graphql.Type`.
type GraphqlTyped interface {
// GraphqlType returns the `graphql.Type` that represents the data type that
// implements this interface.
GraphqlType() graphql.Type
}
var (
graphqlTypedType = reflect.TypeOf(new(GraphqlTyped)).Elem()
graphqlResolverType = reflect.TypeOf(new(GraphqlResolver)).Elem()
timeType = reflect.TypeOf(time.Time{})
)
func (enc *encoder) buildFieldType(fieldType reflect.Type) (graphql.Type, error) {
if r, ok := enc.getType(fieldType); ok {
return r, nil
}
if fieldType.Kind() == reflect.Struct && fieldType != timeType {
// If the type is a struct, we need the a pointer to that struct to
// check if it implements the interface.
tStruct := reflect.PtrTo(fieldType)
if tStruct.Implements(graphqlTypedType) {
vStruct := reflect.New(fieldType)
return vStruct.Interface().(GraphqlTyped).GraphqlType(), nil
}
}
if fieldType.Implements(graphqlTypedType) {
vStruct := reflect.New(fieldType.Elem())
return vStruct.Interface().(GraphqlTyped).GraphqlType(), nil
}
// Check if it is a pointer or interface...
if fieldType.Kind() == reflect.Ptr {
// Updates the type with the type of the pointer
fieldType = fieldType.Elem()
}
// Special case: If the type is the time.Time type.
if fieldType == timeType {
return graphql.DateTime, nil
}
switch fieldType.Kind() {
case reflect.Struct:
return enc.StructOf(fieldType)
case reflect.Array, reflect.Slice:
return enc.ArrayOf(fieldType.Elem())
case reflect.Bool:
return graphql.Boolean, nil
case reflect.String:
return graphql.String, nil
case
reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8,
reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
return graphql.Int, nil
case
reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
return graphql.Float, nil
}
return nil, NewErrTypeNotRecognized(fieldType)
}