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

Force optional args to accept null #18

Open
captbaritone opened this issue Oct 29, 2023 · 2 comments
Open

Force optional args to accept null #18

captbaritone opened this issue Oct 29, 2023 · 2 comments
Labels
bug Something isn't working

Comments

@captbaritone
Copy link
Owner

captbaritone commented Oct 29, 2023

If a field arg is typed in the DSL as optional, a request that passes an explicit null, is considered valid. This means graphql-js will pass through a user's explicit null. This, in turn, means that if Grats is going to generate an optional argument, the user's field resolver must be capable of accepting null.

Today it's possible to define a function which is not expecting in its typescript types, but could get passed a null at runtime:

/** @gqlType */
export default class Query {
  /** @gqlField */
  someField(args: {greeting: string | undefined}): string {
    if(args.greeting === undefined) {
      return "Hello!"
    }
    return args.greeting; // OOPS! Might return `null` here, which is not a `string`.
  }
}
type Query {
  someField(greeting: String): String
}

Playground

I think the best solution here is for Grats to error in this case and force you to add | null to the argument's type.

@captbaritone captbaritone added the bug Something isn't working label Oct 29, 2023
@mandx
Copy link
Contributor

mandx commented Oct 30, 2023

IMO it's the only type-safe solution, since Grats can't/won't alter how graphql-js handles this case?

@captbaritone
Copy link
Owner Author

In theory when we do applyServerDirectves (or in some similar place) we could wrap the resolver functions to match what the user-defined code expects, but I think that's probably not the right direction to head.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants