-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen_schema.go
84 lines (68 loc) · 1.84 KB
/
gen_schema.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
package entx
import (
"embed"
"html/template"
"log"
"os"
"path/filepath"
"strings"
"entgo.io/ent/entc/gen"
"github.com/stoewer/go-strcase"
)
var (
//go:embed templates/*
_templates embed.FS
)
// schema data for template
type schema struct {
Name string
}
// GenSchema generates graphql schemas when not specified to be skipped
func GenSchema(graphSchemaDir string) gen.Hook {
return func(next gen.Generator) gen.Generator {
return gen.GenerateFunc(func(g *gen.Graph) error {
// create schema template
tmpl := createTemplate()
// loop through all nodes and generate schema if not specified to be skipped
for _, node := range g.Nodes {
// check skip annotation
if sg, ok := node.Annotations[SchemaGenAnnotationName]; ok {
val := sg.(map[string]interface{})["Skip"]
if val.(bool) {
continue
}
}
filePath := filepath.Clean(graphSchemaDir + strings.ToLower(node.Name) + ".graphql")
// check if schema already exists, skip generation so we don't overwrite manual changes
if _, err := os.Stat(filePath); err == nil {
continue
}
file, err := os.Create(filePath)
if err != nil {
log.Fatalf("Unable to create file: %v", err)
}
s := schema{
Name: node.Name,
}
// execute template and write to file
if err = tmpl.Execute(file, s); err != nil {
log.Fatalf("Unable to execute template: %v", err)
}
}
return next.Generate(g)
})
}
}
// createTemplate creates a new template for generating graphql schemas
func createTemplate() *template.Template {
// function map for template
fm := template.FuncMap{
"ToLowerCamel": strcase.LowerCamelCase,
}
// create schema template
tmpl, err := template.New("graph.tpl").Funcs(fm).ParseFS(_templates, "templates/graph.tpl")
if err != nil {
log.Fatalf("Unable to parse template: %v", err)
}
return tmpl
}