-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
92 lines (82 loc) · 1.74 KB
/
template.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
package entdataloader
import (
"embed"
"entgo.io/ent/entc/gen"
"fmt"
"text/template"
)
//go:embed template/*.tmpl
var templates embed.FS
var (
DataLoaderTemplate = parse("template/entdataloader.tmpl")
// AllTemplates holds all templates for extending ent to support GraphQL.
AllTemplates = []*gen.Template{
DataLoaderTemplate,
}
)
func hasEdgeField(edge *gen.Edge) bool {
if edge == nil {
return false
}
f := edge.Field()
if f != nil {
return f.IsEdgeField()
}
return false
}
func dataloaderEdge(edge *gen.Edge) (bool, error) {
ant := &Annotation{}
if edge.Annotations != nil && edge.Annotations[ant.Name()] != nil {
if err := ant.Decode(edge.Annotations[ant.Name()]); err != nil {
return false, err
}
switch edge.Rel.Type {
case gen.O2M:
{
isEdgeField := hasEdgeField(edge.Ref)
if isEdgeField {
return true, nil
} else {
return false, fmt.Errorf("edge %s on Type %s does not have an edge field", edge.Name, edge.Type.Name)
}
}
case gen.M2O:
{
return true, nil
}
}
}
return false, nil
}
func dataloaderFieldName(edge *gen.Edge) string {
switch edge.Rel.Type {
case gen.O2M:
return edge.Ref.Field().Name
case gen.M2O:
return edge.Type.ID.Name
}
return "invalid"
}
func dataloaderPlural(edge *gen.Edge) bool {
switch edge.Rel.Type {
case gen.O2M:
return true
case gen.M2O:
return false
}
return false
}
func parse(name string) *gen.Template {
bytes, err := templates.ReadFile(name)
if err != nil {
panic(err)
}
return gen.MustParse(gen.NewTemplate(name).
Funcs(gen.Funcs).
Funcs(template.FuncMap{
"dataloaderEdge": dataloaderEdge,
"dataloaderPlural": dataloaderPlural,
"dataloaderFieldName": dataloaderFieldName,
}).
Parse(string(bytes)))
}