Skip to content

Commit

Permalink
Merge pull request #236 from vektah/generate-handler-on-init
Browse files Browse the repository at this point in the history
Generate server on running init
  • Loading branch information
creativej authored Aug 1, 2018
2 parents 600f467 + 121e8db commit 17bcb32
Show file tree
Hide file tree
Showing 7 changed files with 123 additions and 2 deletions.
15 changes: 13 additions & 2 deletions cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,11 @@ var initCmd = &cobra.Command{
initSchema()
config := initConfig()

generateGraph(config)
GenerateGraphServer(config)
},
}

func generateGraph(config *codegen.Config) {
func GenerateGraphServer(config *codegen.Config) {
schemaRaw, err := ioutil.ReadFile(config.SchemaFilename)
if err != nil {
fmt.Fprintln(os.Stderr, "unable to open schema: "+err.Error())
Expand All @@ -80,10 +80,21 @@ func generateGraph(config *codegen.Config) {
os.Exit(1)
}

if serverFilename == "" {
serverFilename = "server/server.go"
}

if err := codegen.Generate(*config); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}

if err := codegen.GenerateServer(*config, serverFilename); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}

fmt.Fprintln(os.Stdout, `Exec "go run ./server/server.go" to start GraphQL server`)
}

func initConfig() *codegen.Config {
Expand Down
2 changes: 2 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ var schemaFilename string
var typemap string
var packageName string
var modelPackageName string
var serverFilename string

func init() {
rootCmd.PersistentFlags().StringVarP(&configFilename, "config", "c", "", "the file to configuration to")
rootCmd.PersistentFlags().StringVarP(&serverFilename, "server", "s", "", "the file to write server to")
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "show logs")

rootCmd.PersistentFlags().StringVar(&output, "out", "", "the file to write to")
Expand Down
20 changes: 20 additions & 0 deletions codegen/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ type ResolverBuild struct {
ResolverFound bool
}

type ServerBuild struct {
PackageName string
Imports []*Import
ExecPackageName string
ResolverPackageName string
}

// Create a list of models that need to be generated
func (cfg *Config) models() (*ModelBuild, error) {
namedTypes := cfg.buildNamedTypes()
Expand Down Expand Up @@ -99,6 +106,19 @@ func (cfg *Config) resolver() (*ResolverBuild, error) {
}, nil
}

func (cfg *Config) server(destDir string) *ServerBuild {
imports := buildImports(NamedTypes{}, destDir)
imports.add(cfg.Exec.ImportPath())
imports.add(cfg.Resolver.ImportPath())

return &ServerBuild{
PackageName: cfg.Resolver.Package,
Imports: imports.finalize(),
ExecPackageName: cfg.Exec.Package,
ResolverPackageName: cfg.Resolver.Package,
}
}

// bind a schema together with some code to generate a Build
func (cfg *Config) bind() (*Build, error) {
namedTypes := cfg.buildNamedTypes()
Expand Down
22 changes: 22 additions & 0 deletions codegen/codegen.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,28 @@ func Generate(cfg Config) error {
return nil
}

func GenerateServer(cfg Config, filename string) error {
if err := cfg.Exec.normalize(); err != nil {
return errors.Wrap(err, "exec")
}
if err := cfg.Resolver.normalize(); err != nil {
return errors.Wrap(err, "resolver")
}

serverFilename := abs(filename)
serverBuild := cfg.server(filepath.Dir(serverFilename))

if _, err := os.Stat(serverFilename); os.IsNotExist(errors.Cause(err)) {
err = templates.RenderToFile("server.gotpl", serverFilename, serverBuild)
if err != nil {
return errors.Wrap(err, "generate server failed")
}
} else {
log.Printf("Skipped server: %s already exists\n", serverFilename)
}
return nil
}

func generateResolver(cfg Config) error {
resolverBuild, err := cfg.resolver()
if err != nil {
Expand Down
43 changes: 43 additions & 0 deletions codegen/codegen_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package codegen

import (
"syscall"
"testing"

"github.com/stretchr/testify/require"
"golang.org/x/tools/go/loader"
)

func TestGenerateServer(t *testing.T) {
name := "graphserver"
schema := `
type Query {
user(): User
}
type User {
id: Int
}
`
serverFilename := "tests/gen/" + name + "/server/server.go"
cfg := Config{
SchemaStr: schema,
Exec: PackageConfig{Filename: "tests/gen/" + name + "/exec.go"},
Model: PackageConfig{Filename: "tests/gen/" + name + "/model.go"},
Resolver: PackageConfig{Filename: "tests/gen/" + name + "/resolver.go", Type: "Resolver"},
}

_ = syscall.Unlink(cfg.Resolver.Filename)
_ = syscall.Unlink(serverFilename)

err := Generate(cfg)
require.NoError(t, err)

err = GenerateServer(cfg, serverFilename)
require.NoError(t, err)

conf := loader.Config{}
conf.CreateFromFilenames("tests/gen/"+name, serverFilename)

_, err = conf.Load()
require.NoError(t, err)
}
1 change: 1 addition & 0 deletions codegen/templates/data.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions codegen/templates/server.gotpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package main

import (
{{- range $import := .Imports }}
{{- $import.Write }}
{{ end }}
)

const defaultPort = "8080"

func main() {
port := os.Getenv("PORT")
if port == "" {
port = defaultPort
}

http.Handle("/", handler.Playground("GraphQL playground", "/query"))
http.Handle("/query", handler.GraphQL({{.ExecPackageName}}.NewExecutableSchema({{.ExecPackageName}}.Config{Resolvers: &{{.ResolverPackageName}}.Resolver{}})))

log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
log.Fatal(http.ListenAndServe(":" + port, nil))
}

0 comments on commit 17bcb32

Please sign in to comment.