Skip to content

client-preset with nested fragment for union type may generates fragment types that use undefined fragment types #10920

Description

@jet2jet

Which packages are impacted by your issue?

@graphql-codegen/client-preset

Describe the bug

When using client preset, codegen generates unexpected invalid type definitions for nested fragment reference (*) for union type. In particular, fragment type definitions for unused (non-referenced) types of union are not emitted, although they are used from another fragment type definitions.

(*) The fragments are such as:

// type User = Human | Robot

const HumanNameFragment = graphql(`
  fragment HumanName_User on User {
    ... on Human {
      name
    }
  }
`);

const TaskUserFragment = graphql(`
  fragment TaskUser_User on User {
    ... on Human {
      id
    }
    ... on Robot {
      id
    }
    ...HumanName_User
  }
`);

const TaskDetailFragment = graphql(`
  fragment TaskDetail_Task on Task {
    id
    assignee {
      ...TaskUser_User
    }
  }
`);

const GetTaskDocument = graphql(`
  query GetTask($id: String!) {
    task(id: $id) {
      ...TaskDetail_Task
    }
  }
`);

Your Example Website or App

https://github.com/jet2jet/graphql-code-generator-issue-fragment-type-undefined

Steps to Reproduce the Bug or Issue

  1. Clone the repository above
  2. Run npm ci and npm run codegen
  3. Run npm run typecheck to check type definitions

Expected behavior

No error is reported for npm run typecheck

Screenshots or Videos

No response

Platform

  • OS: Linux (WSL)
  • NodeJS: 24.16.0
  • graphql version: 16.14.2
  • @graphql-codegen/cli version(s): 7.2.0
  • @graphql-codegen/client-preset version(s): 6.1.3

Codegen Config File

import { CodegenConfig } from "@graphql-codegen/cli";

const config: CodegenConfig = {
  schema: "schema.graphql",
  generates: {
    'src/gql/': {
      documents: ['src/**/*.mts', '!src/gql/**/*'],
      preset: 'client',
      config: {
        nonOptionalTypename: process.env.WITH_TYPENAME === '1', // for test
      },
    },
  },
};

export default config;

Additional context

If nonOptionalTypename is set to true, all fragment types are emitted correctly, which results no error.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions