github.com/fortexxx/gqlgen@v0.10.3-0.20191216030626-ca5ea8b21ead/api/generate.go (about) 1 package api 2 3 import ( 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/federation" 10 "github.com/99designs/gqlgen/plugin/modelgen" 11 "github.com/99designs/gqlgen/plugin/resolvergen" 12 "github.com/99designs/gqlgen/plugin/schemaconfig" 13 "github.com/pkg/errors" 14 "golang.org/x/tools/go/packages" 15 ) 16 17 func Generate(cfg *config.Config, option ...Option) error { 18 _ = syscall.Unlink(cfg.Exec.Filename) 19 if cfg.Model.IsDefined() { 20 _ = syscall.Unlink(cfg.Model.Filename) 21 } 22 23 if err := cfg.Check(); err != nil { 24 return err 25 } 26 27 plugins := []plugin.Plugin{schemaconfig.New()} 28 if cfg.Model.IsDefined() { 29 plugins = append(plugins, modelgen.New()) 30 } 31 32 plugins = append(plugins, resolvergen.New()) 33 34 if cfg.Federated { 35 plugins = append([]plugin.Plugin{federation.New()}, plugins...) 36 } 37 38 for _, o := range option { 39 o(cfg, &plugins) 40 } 41 42 schemaMutators := []codegen.SchemaMutator{} 43 for _, p := range plugins { 44 if inj, ok := p.(plugin.SourcesInjector); ok { 45 inj.InjectSources(cfg) 46 } 47 if mut, ok := p.(codegen.SchemaMutator); ok { 48 schemaMutators = append(schemaMutators, mut) 49 } 50 } 51 52 for _, p := range plugins { 53 if mut, ok := p.(plugin.ConfigMutator); ok { 54 err := mut.MutateConfig(cfg) 55 if err != nil { 56 return errors.Wrap(err, p.Name()) 57 } 58 } 59 } 60 61 // Merge again now that the generated models have been injected into the typemap 62 data, err := codegen.BuildData(cfg, schemaMutators) 63 if err != nil { 64 return errors.Wrap(err, "merging type systems failed") 65 } 66 67 if err = codegen.GenerateCode(data); err != nil { 68 return errors.Wrap(err, "generating code failed") 69 } 70 71 for _, p := range plugins { 72 if mut, ok := p.(plugin.CodeGenerator); ok { 73 err := mut.GenerateCode(data) 74 if err != nil { 75 return errors.Wrap(err, p.Name()) 76 } 77 } 78 } 79 80 if err = codegen.GenerateCode(data); err != nil { 81 return errors.Wrap(err, "generating core failed") 82 } 83 84 if !cfg.SkipValidation { 85 if err := validate(cfg); err != nil { 86 return errors.Wrap(err, "validation failed") 87 } 88 } 89 90 return nil 91 } 92 93 func validate(cfg *config.Config) error { 94 roots := []string{cfg.Exec.ImportPath()} 95 if cfg.Model.IsDefined() { 96 roots = append(roots, cfg.Model.ImportPath()) 97 } 98 99 if cfg.Resolver.IsDefined() { 100 roots = append(roots, cfg.Resolver.ImportPath()) 101 } 102 _, err := packages.Load(&packages.Config{Mode: packages.LoadTypes | packages.LoadSyntax}, roots...) 103 if err != nil { 104 return errors.Wrap(err, "validation failed") 105 } 106 return nil 107 }