graphql-code-generator icon indicating copy to clipboard operation
graphql-code-generator copied to clipboard

[typescript-type-graphql] generated input optional field are not optional

Open jvolonda42 opened this issue 3 years ago • 0 comments

Describe the bug

When using typescript-type-graphql, the optional fields from an input are not optional

Your Example Website or App

https://codesandbox.io/s/sparkling-hooks-sf2bed?file=/types.ts

Steps to Reproduce the Bug or Issue

Generate type.ts from codesandbox

Expected behavior

As A user I expect optional field generated to be optional

Here is a schema.gql

scalar Date

schema {
  query: Query
  mutation: Mutation
}

type Query {
  me: User!
  user(id: ID!): User
}

input CreateUserInput {
  username: String!
  role: String
}

type Mutation {
  createUser(input: CreateUserInput!): User!
}

type User {
  id: ID!
  username: String!
  email: String!
  role: String
}

The expected output for CreateUserInput should be

@TypeGraphQL.InputType()
export class CreateUserInput {

  @TypeGraphQL.Field(type => String)
  username!: Scalars['String'];

  @TypeGraphQL.Field(type => String, { nullable: true })
  role!: Maybe<Scalars['String']>;
};

instead of

@TypeGraphQL.InputType()
export class CreateUserInput {

  @TypeGraphQL.Field(type => String)
  username!: Scalars['String'];

  @TypeGraphQL.Field(type => String, { nullable: true })
  role!: Maybe<Scalars['String']>;
};

Screenshots or Videos

Screenshot from 2022-06-30 18-21-12

The generated field role should be optional and ! should be replaced with ?

Platform

  • OS: [Linux]
  • NodeJS: [16.15.1]
  • graphql version: [15.3.0]
  • @graphql-codegen/cli version(s): [ 2.6.2]
  • @graphql-codegen/typescript-type-graphql version(s): [ 2.2.14]

Codegen Config File

generates: types.ts: plugins: - typescript-type-graphql

Additional context

I think the problem is from this file: packages/plugins/typescript/type-graphql/src/visitor.ts

Line 454 should be replaced with return decorator + indent(`${this.config.immutableTypes ? 'readonly ' : ''}${nameString}${type.isNullable ? '?' : '!'}: ${typeString};`); instead of return decorator + visitorPluginCommon.indent(`${this.config.immutableTypes ? 'readonly ' : ''}${nameString}!: ${typeString};`);

I would be open to make a PR with this change if you confirm me that it's a bug

jvolonda42 avatar Jun 30 '22 16:06 jvolonda42