Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generates enum that is listed in types.json #71

Closed
jonlundy opened this issue Mar 31, 2018 · 3 comments
Closed

Generates enum that is listed in types.json #71

jonlundy opened this issue Mar 31, 2018 · 3 comments

Comments

@jonlundy
Copy link
Contributor

I added a custom enum type to types.json and use it in my graphql spec.

Expected Behaviour

gqlgen would use the custom type instead of generating enum into models_gen.go

Actual Behavior

enum code is generated into models_gen.go and a mismatch error is reported

type mismatch on Foo.state, expected <package>/foo.FooState got <package>/foo/custom.FooState

Minimal graphql.schema and models to reproduce

graph.graphql:

type Query {
    foo(): Foo!
}

type Foo {
    state: FooState!
}

enum FooState {
    BIN
    BAR
    BAZ
}

types.json:

{
  "FooState": "<package>/foo/custom.FooState"
}

custom/foo.go:

package custom

import (
	"fmt"
	"io"
	"strconv"
)

type FooState string

const (
	FooStateBin FooState = "BIN"
	FooStateBar FooState = "BAR"
	FooStateBaz FooState = "BAZ"
)

func (e FooState) IsValid() bool {
	switch e {
	case FooStateBin, FooStateBar, FooStateBaz:
		return true
	}
	return false
}

func (e FooState) String() string {
	return string(e)
}

func (e *FooState) UnmarshalGQL(v interface{}) error {
	str, ok := v.(string)
	if !ok {
		return fmt.Errorf("enums must be strings")
	}

	*e = FooState(str)
	if !e.IsValid() {
		return fmt.Errorf("%s is not a valid FooState", str)
	}
	return nil
}

func (e FooState) MarshalGQL(w io.Writer) {
	fmt.Fprint(w, strconv.Quote(e.String()))
}
@jonlundy
Copy link
Contributor Author

I have managed to work around this issue using the newly added -modelpackage flag so that it generates the enum into the same folder as my custom models

@vektah
Copy link
Collaborator

vektah commented Apr 1, 2018

Thanks for the bug report, should be fixed now.

I updated model to take directory names so enums could live with the other models, otherwise you end up with import loops pretty quickly.

What was the reason you needed a custom enum? Is it common enough to be worth folding into the generated enum?

@vektah vektah closed this as completed in #72 Apr 1, 2018
@jonlundy
Copy link
Contributor Author

jonlundy commented Apr 1, 2018

I was attempting to avoid import loops and keep my models together. The new flag for module dir is exactly what I needed.

It looks like the module code is still using -package

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants