forked from Yamashou/gqlgenc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generater.go
60 lines (51 loc) · 1.42 KB
/
generater.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
package generator
import (
"context"
"fmt"
"github.com/99designs/gqlgen/api"
codegenconfig "github.com/99designs/gqlgen/codegen/config"
"github.com/99designs/gqlgen/plugin"
"github.com/99designs/gqlgen/plugin/modelgen"
"github.com/maxtroughear/gqlgenc/config"
)
// mutateHook adds the "omitempty" option to nilable fields.
// For more info see https://github.com/99designs/gqlgen/blob/master/docs/content/recipes/modelgen-hook.md
func mutateHook(b *modelgen.ModelBuild) *modelgen.ModelBuild {
for _, model := range b.Models {
for _, field := range model.Fields {
field.Tag = `json:"` + field.Name
if codegenconfig.IsNilable(field.Type) {
field.Tag += ",omitempty"
}
field.Tag += `"`
}
}
return b
}
func Generate(ctx context.Context, cfg *config.Config, option ...api.Option) error {
var plugins []plugin.Plugin
if cfg.Model.IsDefined() {
p := modelgen.Plugin{
MutateHook: mutateHook,
}
plugins = append(plugins, &p)
}
for _, o := range option {
o(cfg.GQLConfig, &plugins)
}
if err := cfg.LoadSchema(ctx); err != nil {
return fmt.Errorf("failed to load schema: %w", err)
}
if err := cfg.GQLConfig.Init(); err != nil {
return fmt.Errorf("generating core failed: %w", err)
}
for _, p := range plugins {
if mut, ok := p.(plugin.ConfigMutator); ok {
err := mut.MutateConfig(cfg.GQLConfig)
if err != nil {
return fmt.Errorf("%s failed: %w", p.Name(), err)
}
}
}
return nil
}