1package api
2
3import (
4 "syscall"
5
6 "github.com/99designs/gqlgen/codegen"
7 "github.com/99designs/gqlgen/codegen/config"
8 "github.com/99designs/gqlgen/plugin"
9 "github.com/99designs/gqlgen/plugin/modelgen"
10 "github.com/99designs/gqlgen/plugin/resolvergen"
11 "github.com/99designs/gqlgen/plugin/schemaconfig"
12 "github.com/pkg/errors"
13 "golang.org/x/tools/go/packages"
14)
15
16func Generate(cfg *config.Config, option ...Option) error {
17 _ = syscall.Unlink(cfg.Exec.Filename)
18 _ = syscall.Unlink(cfg.Model.Filename)
19
20 plugins := []plugin.Plugin{
21 schemaconfig.New(),
22 modelgen.New(),
23 resolvergen.New(),
24 }
25
26 for _, o := range option {
27 o(cfg, &plugins)
28 }
29
30 for _, p := range plugins {
31 if mut, ok := p.(plugin.ConfigMutator); ok {
32 err := mut.MutateConfig(cfg)
33 if err != nil {
34 return errors.Wrap(err, p.Name())
35 }
36 }
37 }
38 // Merge again now that the generated models have been injected into the typemap
39 data, err := codegen.BuildData(cfg)
40 if err != nil {
41 return errors.Wrap(err, "merging failed")
42 }
43
44 if err = codegen.GenerateCode(data); err != nil {
45 return errors.Wrap(err, "generating core failed")
46 }
47
48 for _, p := range plugins {
49 if mut, ok := p.(plugin.CodeGenerator); ok {
50 err := mut.GenerateCode(data)
51 if err != nil {
52 return errors.Wrap(err, p.Name())
53 }
54 }
55 }
56
57 if err := validate(cfg); err != nil {
58 return errors.Wrap(err, "validation failed")
59 }
60
61 return nil
62}
63
64func validate(cfg *config.Config) error {
65 roots := []string{cfg.Exec.ImportPath()}
66 if cfg.Model.IsDefined() {
67 roots = append(roots, cfg.Model.ImportPath())
68 }
69
70 if cfg.Resolver.IsDefined() {
71 roots = append(roots, cfg.Resolver.ImportPath())
72 }
73 _, err := packages.Load(&packages.Config{Mode: packages.LoadTypes | packages.LoadSyntax}, roots...)
74 if err != nil {
75 return errors.Wrap(err, "validation failed")
76 }
77 return nil
78}