-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
interface.go
87 lines (70 loc) · 2.12 KB
/
interface.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
package codegen
import (
"fmt"
"go/types"
"github.com/vektah/gqlparser/v2/ast"
"github.com/99designs/gqlgen/codegen/config"
)
type Interface struct {
*ast.Definition
Type types.Type
Implementors []InterfaceImplementor
InTypemap bool
}
type InterfaceImplementor struct {
*ast.Definition
Type types.Type
TakeRef bool
}
func (b *builder) buildInterface(typ *ast.Definition) (*Interface, error) {
obj, err := b.Binder.DefaultUserObject(typ.Name)
if err != nil {
panic(err)
}
i := &Interface{
Definition: typ,
Type: obj,
InTypemap: b.Config.Models.UserDefined(typ.Name),
}
interfaceType, err := findGoInterface(i.Type)
if interfaceType == nil || err != nil {
return nil, fmt.Errorf("%s is not an interface", i.Type)
}
for _, implementor := range b.Schema.GetPossibleTypes(typ) {
obj, err := b.Binder.DefaultUserObject(implementor.Name)
if err != nil {
return nil, fmt.Errorf("%s has no backing go type", implementor.Name)
}
implementorType, err := findGoNamedType(obj)
if err != nil {
return nil, fmt.Errorf("can not find backing go type %s: %w", obj.String(), err)
} else if implementorType == nil {
return nil, fmt.Errorf("can not find backing go type %s", obj.String())
}
anyValid := false
// first check if the value receiver can be nil, eg can we type switch on case Thing:
if types.Implements(implementorType, interfaceType) {
i.Implementors = append(i.Implementors, InterfaceImplementor{
Definition: implementor,
Type: obj,
TakeRef: !types.IsInterface(obj),
})
anyValid = true
}
// then check if the pointer receiver can be nil, eg can we type switch on case *Thing:
if types.Implements(types.NewPointer(implementorType), interfaceType) {
i.Implementors = append(i.Implementors, InterfaceImplementor{
Definition: implementor,
Type: types.NewPointer(obj),
})
anyValid = true
}
if !anyValid {
return nil, fmt.Errorf("%s does not satisfy the interface %s", implementorType.String(), i.Type.String())
}
}
return i, nil
}
func (i *InterfaceImplementor) CanBeNil() bool {
return config.IsNilable(i.Type)
}