dotansimha / dotansimha/graphql-code-generator

Model fields skipped with directives different than optional types

Open
#9,476 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
11.3k
Forks
1.4k
Avg merge
1d 1h
Merged PRs (30d)
23

Description

### Is your feature request related to a problem? Please describe.

I'm trying to model the actual GraphQL return type for operations with codegen and it doesn't seem to be possible. Imagine this schema:

```graphql
type Query {
foo: String
bar: String!
baz: String
}
```

And the following operation:

```graphql
query Example($includeBar: Boolean!) {
foo
...OptionalFields @include(if: $includeBar)
}

fragment OptionalFields on Query {
bar
baz
}
```

What GraphQL actually returns would be typed like this

```ts
type OptionalFields = { bar: string, baz: string | null }
type Example = { foo: string | null } | ({ foo: string | null } & OptionalFields)
```

Currently, I can choose to have `avoidOptionals: false` and get

```ts
type Example = {
foo?: string | null,
bar?: string | null,
baz?: string | null,
}
```

which is too permissive, as it allows any field to be missing or `null`, or choose `avoidOptionals: true` and get

```ts
type Example = {
foo: string | null,
bar: string | null,
baz: string | null,
}
```

which cannot model the fact that `bar` and `baz` can be missing but `bar` cannot be `null`.

### Describe the solution you'd like

It would be great if fields skipped with directives could be modelled as unions of the different possible types instead of just making any non-optional fields affected by the directives optional, regardless of what `avoidOptionals` is set to.

### Describe alternatives you've considered

If unions are considered too unwieldy or unperformant, a decent compromise would be to have a configuration that would generate something like

```ts
type Example = {
foo: string | null,
bar?: string,
baz?: string | null
}
```

This is not quite as accurate as the union of different possibilities but at least it has the right information as to what fields can be `null` and what fields can be `undefined`

### Is your feature request related to a problem? Please describe.

_No response_

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.