dotansimha / dotansimha/graphql-code-generator

Support `@required` and `@optional` directives

Open
#10,453 4 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'd like to add built-in support for _any_ method that could generate the following TypeScript types from a schema for use by a client:

```ts
export type MyInput = {
a?: InputMaybe;
b?: Scalars['String']['input'];
c: InputMaybe;
d: Scalars['String']['input'];
};
```

### Describe the solution you'd like

The best proposal I've seen uses `@required` and `@optional` input directives, as described in https://github.com/graphql/graphql-spec/issues/872:

```graphql
"""
This input is optional, not nullable.
If the client insists on sending an explicit null value, the behavior is undefined.
"""
directive @optional on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION

"""
This input is nullable, not optional.
If the client insists on omitting the input value, the behavior is undefined.
"""
directive @required on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION

input MyInput {
a: String
b: String @optional
c: String @required
d: String!
}
```

This addresses a [very common concern](https://github.com/graphql/graphql-spec/issues/476), and since it only uses directives, it's completely forward- and backward-compatible and doesn't require any changes to the GraphQL spec.

My suggestion is to support the above with a new TypeScript plugin option:

```ts
export default {
generates: {
"path/to/file": {
config: {
directiveArgumentAndInputFieldNarrowing: {
nonNullable: "optional",
nonOptional: "required",
},
},
},
},
} satisfies CodegenConfig;
```

### Describe alternatives you've considered

_No response_

### Any additional important details?

If we could agree on the right approach, I'd be happy to try implementing this myself.

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.