Gqlgen: Type as field in a model, what to do?

Created on 16 Jun 2020  路  5Comments  路  Source: 99designs/gqlgen

If I have a model like this:

type Player struct {
  Kind  PlayerType
}

type PlayerType int

const (
  Zombie PlayerType = iota
  Human
  Dog
)

and a schema like this:

type Player {
  kind: Int!
}

it generates method in resolver for Kind:

func (r *playerResolver) Kind(ctx context.Context, obj *Player) (int, error) {
  panic(fmt.Errorf("not implemented"))
}

but PlayerType is just a new type based on int.

How to fix this?

I need to write something in config.yml?

versions

  • gqlgen version? v0.11.3
  • go version? go1.14.3 windows/amd64
  • dep or go modules? go mod

Most helpful comment

One solution would be to create a scalar type on the graphql side and then bind that to your go type.

see https://github.com/99designs/gqlgen/tree/master/example/scalars for examples of this.

All 5 comments

I think I can jump in on this (and happy to be told that this isn't quite correct).

func (r *playerResolver) Kind(ctx context.Context, obj *Player) (int, error) {
  return int(obj.Kind), nil
}

Because PlayerType is a specific type based on int it still needs to be cast as one.

One solution would be to create a scalar type on the graphql side and then bind that to your go type.

see https://github.com/99designs/gqlgen/tree/master/example/scalars for examples of this.

That's probably a neater solution right there @lwc!

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Thanks for your answers.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

huanghantao picture huanghantao  路  3Comments

lynntobing picture lynntobing  路  3Comments

sumanthakannantha picture sumanthakannantha  路  3Comments

andrewmunro picture andrewmunro  路  4Comments

kevinmbeaulieu picture kevinmbeaulieu  路  3Comments