Skip to content

Commit

Permalink
fix: change cwd to load gqlgen config correctly (#103)
Browse files Browse the repository at this point in the history
Code copied from 99designs/gqlgen#1511
  • Loading branch information
giautm authored and a8m committed Jul 8, 2021
1 parent 266b8fe commit 7344a46
Show file tree
Hide file tree
Showing 10 changed files with 246 additions and 247 deletions.
81 changes: 39 additions & 42 deletions entgql/extension.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package entgql
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"

Expand All @@ -31,7 +32,6 @@ import (
"github.com/graphql-go/graphql/language/printer"
"github.com/graphql-go/graphql/language/source"
"github.com/graphql-go/graphql/language/visitor"
gqlparserast "github.com/vektah/gqlparser/v2/ast"
)

type (
Expand All @@ -51,16 +51,19 @@ type (
ExtensionOption func(*Extension) error
)

// WithSchemaPath sets the filepath to load the GraphQL schema from.
// It fails if the schema can't be opened or is not parsable.
// WithSchemaPath sets the filepath to the GraphQL schema to write the
// generated Ent types. If the file does not exist, it will generate a
// new schema. Please note, that your gqlgen.yml config file should be
// updated as follows to support multiple schema files:
//
// schema:
// - schema.graphql // existing schema.
// - ent.graphql // generated schema.
//
// Note that, if this option was provided, the extension appends
// or updates the GraphQL schema with the generated input types,
// and injects its parsed schema to the global annotations.
func WithSchemaPath(path string) ExtensionOption {
return func(ex *Extension) error {
buf, err := ioutil.ReadFile(path)
if err != nil {
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("reading graphql schema %q: %w", path, err)
}
ex.doc, err = parser.Parse(parser.ParseParams{
Expand All @@ -78,38 +81,52 @@ func WithSchemaPath(path string) ExtensionOption {
}
}

// GQLConfigAnnotation is the annotation key/name that holds gqlgen
// configuration if it was provided by the `WithConfigPath` option.
const GQLConfigAnnotation = "GQLConfig"

// WithConfigPath sets the filepath to gqlgen.yml configuration file
// and injects its parsed version to the global annotations.
//
// Note that, enabling this option is recommended as it improves the
// GraphQL integration,
func WithConfigPath(path string) ExtensionOption {
return func(ex *Extension) error {
cfg, err := config.LoadConfig(path)
return func(ex *Extension) (err error) {
cwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("unable to get working directory: %w", err)
}
if err := os.Chdir(filepath.Dir(path)); err != nil {
return fmt.Errorf("unable to enter config dir: %w", err)
}
defer func() {
if cerr := os.Chdir(cwd); cerr != nil {
err = fmt.Errorf("unable to restore working directory: %w", cerr)
}
}()
cfg, err := config.LoadConfig(filepath.Base(path))
if err != nil {
return err
}

if cfg.Schema == nil {
if err := cfg.LoadSchema(); err != nil {
return err
}
}

ex.cfg = cfg
ex.hooks = append(ex.hooks, func(next gen.Generator) gen.Generator {
return gen.GenerateFunc(func(g *gen.Graph) error {
if g.Annotations == nil {
g.Annotations = gen.Annotations{}
}
g.Annotations[GQLConfigAnnotation] = cfg
return next.Generate(g)
})
})
return nil
}
}

const (
// GQLConfigAnnotation is the annotation key/name that holds gqlgen
// configuration if it was provided by the `WithConfigPath` option.
GQLConfigAnnotation = "GQLConfig"
// GQLSchemaAnnotation is the annotation key/name that holds parsed
// GraphQL schema if it was provided by the `WithSchemaPath` option.
GQLSchemaAnnotation = "GQLSchema"
)

// WithTemplates overrides the default templates (entgql.AllTemplates)
// with specific templates.
func WithTemplates(templates ...*gen.Template) ExtensionOption {
Expand Down Expand Up @@ -181,24 +198,7 @@ func (e *Extension) Templates() []*gen.Template {

// Hooks of the extension.
func (e *Extension) Hooks() []gen.Hook {
var hooks []gen.Hook
if e.cfg != nil || e.doc != nil {
hooks = append(hooks, func(next gen.Generator) gen.Generator {
return gen.GenerateFunc(func(g *gen.Graph) error {
if g.Annotations == nil {
g.Annotations = gen.Annotations{}
}
if e.cfg != nil {
g.Annotations[GQLConfigAnnotation] = e.cfg
}
if e.doc != nil {
g.Annotations[GQLSchemaAnnotation] = e.doc
}
return next.Generate(g)
})
})
}
return append(hooks, e.hooks...)
return e.hooks
}

// mapScalar provides maps an ent.Schema type into GraphQL scalar type.
Expand Down Expand Up @@ -271,11 +271,8 @@ func (e *Extension) hasMapping(f *gen.Field) (string, bool) {
// isInput reports if the given type is an input object.
func (e *Extension) isInput(name string) bool {
if t, ok := e.cfg.Schema.Types[name]; ok && t != nil {
return t.Kind == gqlparserast.Enum ||
t.Kind == gqlparserast.Scalar ||
t.Kind == gqlparserast.InputObject
return t.IsInputType()
}

return false
}

Expand Down
97 changes: 97 additions & 0 deletions entgql/internal/todo/ent.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"""
CategoryWhereInput is used for filtering Category objects.
Input was generated by ent.
"""
input CategoryWhereInput {
not: CategoryWhereInput
and: [CategoryWhereInput!]
or: [CategoryWhereInput!]

"""text field predicates"""
text: String
textNEQ: String
textIn: [String!]
textNotIn: [String!]
textGT: String
textGTE: String
textLT: String
textLTE: String
textContains: String
textHasPrefix: String
textHasSuffix: String
textEqualFold: String
textContainsFold: String

"""status field predicates"""
status: CategoryStatus
statusNEQ: CategoryStatus
statusIn: [CategoryStatus!]
statusNotIn: [CategoryStatus!]

"""todos edge predicates"""
hasTodos: Boolean
hasTodosWith: [TodoWhereInput!]
}

"""
TodoWhereInput is used for filtering Todo objects.
Input was generated by ent.
"""
input TodoWhereInput {
not: TodoWhereInput
and: [TodoWhereInput!]
or: [TodoWhereInput!]

"""created_at field predicates"""
createdAt: Time
createdAtNEQ: Time
createdAtIn: [Time!]
createdAtNotIn: [Time!]
createdAtGT: Time
createdAtGTE: Time
createdAtLT: Time
createdAtLTE: Time

"""status field predicates"""
status: Status
statusNEQ: Status
statusIn: [Status!]
statusNotIn: [Status!]

"""priority field predicates"""
priority: Int
priorityNEQ: Int
priorityIn: [Int!]
priorityNotIn: [Int!]
priorityGT: Int
priorityGTE: Int
priorityLT: Int
priorityLTE: Int

"""text field predicates"""
text: String
textNEQ: String
textIn: [String!]
textNotIn: [String!]
textGT: String
textGTE: String
textLT: String
textLTE: String
textContains: String
textHasPrefix: String
textHasSuffix: String
textEqualFold: String
textContainsFold: String

"""parent edge predicates"""
hasParent: Boolean
hasParentWith: [TodoWhereInput!]

"""children edge predicates"""
hasChildren: Boolean
hasChildrenWith: [TodoWhereInput!]

"""category edge predicates"""
hasCategory: Boolean
hasCategoryWith: [CategoryWhereInput!]
}
2 changes: 1 addition & 1 deletion entgql/internal/todo/ent/entc.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
func main() {
ex, err := entgql.NewExtension(
entgql.WithWhereFilters(true),
entgql.WithSchemaPath("../todo.graphql"),
entgql.WithSchemaPath("../ent.graphql"),
entgql.WithConfigPath("../gqlgen.yml"),
)
if err != nil {
Expand Down
69 changes: 34 additions & 35 deletions entgql/internal/todo/generated.go

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

2 changes: 2 additions & 0 deletions entgql/internal/todo/gqlgen.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

schema:
- todo.graphql
# The ent.graphql schema was generated by Ent.
- ../todo/ent.graphql

resolver:
layout: follow-schema
Expand Down
Loading

0 comments on commit 7344a46

Please sign in to comment.