dotansimha/graphql-code-generator

More control over maybeValue

Open

#5938 opened on May 4, 2021

View on GitHub
 (3 comments) (16 reactions) (0 assignees)TypeScript (10,341 stars) (1,295 forks)batch import
corehelp wantedkind/enhancement

Description

(This was originally requested in #1935, but was closed as a duplicate of #1885 which was incorrect. Hear me out.)

Since a GraphQL optional field may either be missing entirely or explicitly set to null, input types benefit from maybeValue: T | null | undefined. With that input type it is easy to implement deletion of a field by checking for null explicitly in the mutation resolver.

However, now all optional output types can also be null or undefined. In my codebase, we exclusively use undefined as our 'not there' value, which causes some trouble with conversions between types when returning results from resolvers or writing re-usable functions, since the output types are not 100% compatible. This causes as XXX usage, which then sometimes hides other problems.

SO...

If I can generate with config like:

...
  config:
    maybeValue:
      inputValue: T | null | undefined
      others: T | undefined

It'll make the generated types match closer with (my) reality.

In case you're wondering... Using the default maybeValue: T | null hides the fact that undefined are still possible on inputs specifically, especially with the default use of optionals.

I case it's not 100 clear, I would like to achieve this:

  • input types: T | null | undefined for things that are optional in the input type
  • output types: T | undefined for things that are optional in the output type

Can this be done?

EDIT: Why not null as the optional output type? Because if it is returned as a field, additional more-specific resolvers won't be called, since null is valid in that case. Accidentally returning {name: 'cat', kittens: null} will cause the Cat.kittens resolver to not be called, since a valid value is already present, although this may be a bug in the server.

Contributor guide