-
Notifications
You must be signed in to change notification settings - Fork 12
/
union.go
111 lines (100 loc) · 2.61 KB
/
union.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
package gqlengine
import (
"fmt"
"reflect"
"github.com/karfield/graphql"
)
type unionConfig struct {
union graphql.Union
types map[reflect.Type]struct{}
}
func (engine *Engine) PreRegisterUnion(interfacePrototype interface{}, types ...interface{}) error {
unionType := unwrapForKind(interfacePrototype, reflect.Interface)
if unionType == nil {
return fmt.Errorf("")
}
if _, ok := engine.unions[unionType]; ok {
return nil
}
if len(types) == 0 {
return fmt.Errorf("missing types")
}
config := &unionConfig{
types: map[reflect.Type]struct{}{},
}
engine.types[unionType] = &config.union
for _, typ := range types {
t := reflect.TypeOf(typ)
_, info, err := engine.asObject(t)
if err != nil {
return fmt.Errorf("%s is not an object: %E", t, err)
}
config.types[info.baseType] = struct{}{}
}
engine.unions[unionType] = config
return nil
}
func (engine *Engine) completeUnions() error {
for ut, uc := range engine.unions {
var types []*graphql.Object
for t := range uc.types {
if ot, ok := engine.types[t]; !ok {
return fmt.Errorf("no such type %s for union %s", t.Name(), ut.Name())
} else if o, ok := ot.(*graphql.Object); !ok {
return fmt.Errorf("type %s is not an object for union %s", ot.Name(), ut.Name())
} else {
types = append(types, o)
}
}
err := graphql.InitUnion(&uc.union, graphql.UnionConfig{
Name: ut.Name(),
Types: types,
Description: "",
ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
pt := reflect.TypeOf(p.Value)
if pt.Implements(ut) {
if info, err := unwrap(reflect.TypeOf(p.Value)); err == nil {
if typ, ok := engine.types[info.baseType]; ok {
if obj, ok := typ.(*graphql.Object); ok {
return obj
}
}
}
}
return nil
},
})
if err != nil {
return fmt.Errorf("init union %s failed %E", ut.Name(), err)
}
}
return nil
}
func (engine *Engine) asUnionResult(p reflect.Type) (*unwrappedInfo, error) {
_, unionType := unwrapInterface(p)
if unionType == nil {
return nil, nil
}
if _, ok := engine.unions[unionType]; ok {
return &unwrappedInfo{
ptrType: unionType,
implType: unionType,
baseType: unionType,
}, nil
}
return nil, nil
}
func (engine *Engine) asUnionField(field *reflect.StructField) (graphql.Type, *unwrappedInfo, error) {
array, unionType := unwrapInterface(field.Type)
if unionType == nil {
return nil, nil, nil
}
if uc, ok := engine.unions[unionType]; ok {
return wrapType(field, &uc.union, array), &unwrappedInfo{
ptrType: unionType,
implType: unionType,
baseType: unionType,
}, nil
}
return nil, nil, nil
}