Skip to content

Commit

Permalink
add import generation
Browse files Browse the repository at this point in the history
  • Loading branch information
Антон Вершинин committed Sep 20, 2023
1 parent 60e4494 commit 8123191
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 25 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module github.com/jkrajniak/graphql-codegen-go
module github.com/VerTox/graphql-codegen-go

go 1.13

Expand Down
70 changes: 49 additions & 21 deletions internal/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,46 +11,49 @@ const (
// This file was generated from GraphQL schema
package %s
%s
`

StructTPL = `type %s struct {
%s
}`

ImportTPL = `import "%s"`
FieldTPL = " %s %s `json:\"%s\"`"
ListFieldTPL = " %s []%s `json:\"%s\"`"
EnumTypeDefTPL = "type %s %s"
EnumDefConstTPL = "const %s%s %s = \"%s\""
)

var GQLTypesToGoTypes = map[string]string{
"Int": "int64",
"Float": "float64",
"String": "string",
"Boolean": "bool",
"ID": "string",
"Int": "int64",
"Float": "float64",
"String": "string",
"Boolean": "bool",
"ID": "string",
"Long": "int64",
"DateTime": "time.Time",
"UUID": "uuid.UUID",
}

var ImportedLibs = map[string]string{
"uuid.UUID": "github.com/google/uuid",
"time.Time": "time",
}

type GoGenerator struct {
entities []string
enumMapType map[string]string

packageName string
output Outputer
disableHeader bool
packageName string
output Outputer
}

func NewGoGenerator(output Outputer, entities []string, packageName string) *GoGenerator {
return &GoGenerator{output: output, entities: entities, packageName: packageName}
}

func (g *GoGenerator) Generate(doc *ast.SchemaDocument) error {
if !g.disableHeader {
if err := g.output.Writeln(fmt.Sprintf(Header, g.packageName)); err != nil {
return err
}
}

declaredKeywords := keywordMap{}

//remap enums
Expand Down Expand Up @@ -84,6 +87,8 @@ func (g *GoGenerator) Generate(doc *ast.SchemaDocument) error {
}
}

imports := make(map[string]bool, 0)

for _, i := range doc.Definitions {
if len(reqEntities) > 0 && !inArray(i.Name, reqEntities) {
continue
Expand All @@ -94,11 +99,17 @@ func (g *GoGenerator) Generate(doc *ast.SchemaDocument) error {
if i.Kind == ast.Object || i.Kind == ast.InputObject {
var fields []string
for _, f := range i.Fields {
typeName := resolveType(f.Type.Name(), enumMap, f.Type.NonNull)
typeName, importPath := resolveType(f.Type.Name(), enumMap, f.Type.NonNull)
if importPath != "" {
imports[importPath] = true
}
fieldName := strings.Title(f.Name)
jsonFieldName := f.Name
if f.Type.Elem != nil { // list type
elemTypeName := resolveType(f.Type.Elem.Name(), enumMap, f.Type.Elem.NonNull)
elemTypeName, importPath := resolveType(f.Type.Elem.Name(), enumMap, f.Type.Elem.NonNull)
if importPath != "" {
imports[importPath] = true
}
fields = append(fields, fmt.Sprintf(ListFieldTPL, fieldName, elemTypeName, jsonFieldName))
} else {
fields = append(fields, fmt.Sprintf(FieldTPL, fieldName, typeName, jsonFieldName))
Expand All @@ -125,14 +136,27 @@ func (g *GoGenerator) Generate(doc *ast.SchemaDocument) error {
}
}

var importsStr string

for importPath := range imports {
importsStr += "\n" + fmt.Sprintf(ImportTPL, importPath)
}

importsStr += "\n"

err := g.output.WriteToStart(fmt.Sprintf(Header, g.packageName, importsStr))
if err != nil {
return err
}

if missingEntities := declaredKeywords.GetMissingKeys(g.entities); len(missingEntities) > 0 {
return fmt.Errorf("the following entites are not found in graphql schemas: %v", missingEntities)
}

return nil
}

func resolveType(typeName string, enumMap map[string]enum, notNull bool) string {
func resolveType(typeName string, enumMap map[string]enum, notNull bool) (string, string) {
if tName, hasType := GQLTypesToGoTypes[typeName]; hasType {
typeName = tName
}
Expand All @@ -142,9 +166,14 @@ func resolveType(typeName string, enumMap map[string]enum, notNull bool) string
if !notNull { // if type can be nullable, use pointer
typeName = strings.Join([]string{"*", typeName}, "")
}
return typeName
}

importPath, ok := ImportedLibs[typeName]
if ok {
return typeName, importPath
}

return typeName, ""
}

func resolveEntityDependencies(doc *ast.SchemaDocument, reqEntities []string, enumMap map[string]enum) []string {
dependsOn := map[string][]string{}
Expand Down Expand Up @@ -200,4 +229,3 @@ func buildEnumMap(doc *ast.SchemaDocument) map[string]enum {
}
return enumMap
}

12 changes: 12 additions & 0 deletions internal/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

type Outputer interface {
Write(s string) error
WriteToStart(s string) error
Writeln(s string) error
Close() error
Flush() error
Expand All @@ -21,6 +22,11 @@ func NewSTDOutput() *STDOutput {
return &STDOutput{buff: []byte{}}
}

func (o *STDOutput) WriteToStart(s string) error {
o.buff = append([]byte(s), o.buff...)
return nil
}

func (o *STDOutput) Write(s string) error {
o.buff = append(o.buff, []byte(s)...)
return nil
Expand Down Expand Up @@ -62,6 +68,12 @@ func (o *FileOutput) Write(s string) error {
o.buff = append(o.buff, []byte(s)...)
return nil
}

func (o *FileOutput) WriteToStart(s string) error {
o.buff = append([]byte(s), o.buff...)
return nil
}

func (o *FileOutput) Writeln(s string) error {
o.buff = append(o.buff, []byte(s)...)
o.buff = append(o.buff, []byte("\n")...)
Expand Down
4 changes: 2 additions & 2 deletions internal/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package internal

import (
"fmt"
"github.com/jkrajniak/graphql-codegen-go/internal/readers"
"github.com/VerTox/graphql-codegen-go/internal/readers"
"github.com/pkg/errors"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/formatter"
Expand Down Expand Up @@ -33,7 +33,7 @@ func ReadSchemas(schemaPaths []string) ([]InputSchema, error) {
}

func LoadSchemas(inputSchemas []InputSchema) (*ast.SchemaDocument, error) {
sourceSchemas := []*ast.Source{validator.Prelude} // include types
sourceSchemas := []*ast.Source{validator.Prelude} // include types
for _, inputSchema := range inputSchemas {
sourceSchemas = append(sourceSchemas, &ast.Source{
Name: inputSchema.SourcePath,
Expand Down
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package main

import (
"flag"
"github.com/jkrajniak/graphql-codegen-go/internal"
"github.com/VerTox/graphql-codegen-go/internal"
"github.com/pkg/errors"
"os"
"strings"
Expand Down

0 comments on commit 8123191

Please sign in to comment.