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

Directive on Input Type Receives Map instead of Object #3253

Open
Dan6erbond opened this issue Sep 6, 2024 · 1 comment
Open

Directive on Input Type Receives Map instead of Object #3253

Dan6erbond opened this issue Sep 6, 2024 · 1 comment

Comments

@Dan6erbond
Copy link

Dan6erbond commented Sep 6, 2024

What happened?

I wanted to implement a custom directive for input types called @validate.

My directive hook looks like this:

	config.Directives.Validate = func(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) {
		if _, ok := obj.(map[string]any); ok {
			return next(ctx)
		}

		if err := validate.StructCtx(ctx, obj); err != nil {
			return nil, err
		}

		return next(ctx)
	}

What did you expect?

I expected the validate.StructCtx to be called, and obj to be of the type model.CreateCarInput.

Minimal graphql.schema and models to reproduce

directive @validate on OBJECT | INPUT_OBJECT

input CreateCarInput @validate {
  make: String! @goTag(key: "validate", value: "notblank")
  model: String!
  type: String!
  year: Int!
}

versions

  • go run github.com/99designs/gqlgen version v0.17.49
  • go version go version go1.22.3 linux/amd64
@Dan6erbond
Copy link
Author

Upon further investigation on a very barebones schema it seems the directive runs for each field of the input. This makes no sense to me because if I wanted that behavior the validate directive would be configured to be set on INPUT_FIELD_DEFINITION.

Sample schema:

directive @validate on INPUT_OBJECT

type Todo {
  id: ID!
  text: String!
  done: Boolean!
  user: User!
}

type User {
  id: ID!
  name: String!
}

input NewTodo @validate {
  text: String!
  userId: String!
}

type Mutation {
  createTodo(input: NewTodo!): Todo!
}

Directive:

func validate(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) {
	pctx := graphql.GetPathContext(ctx)
	fmt.Println(*pctx.Field)

	res, err = next(ctx)

	fmt.Printf("Validating object %s of type %T\n", res, res)

	return
}

Output:

text
Validating object Test of type string
userId
Validating object 1 of type string

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

1 participant