generate.go

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