heftapp / graphql_codegen

MIT License
143 stars 53 forks source link

Duplicate generated classes #337

Closed SharbelOkzan closed 7 months ago

SharbelOkzan commented 7 months ago

A type in my schema looks like this

type Tournament {
  id: ID!
  // ...
  first_prize: Prize
  second_prize: Prize
  third_prize: Prize
  fourth_prize: Prize
// ... 
}

type Prize {
  id: ID!
  amount: Int
  currency: String
}

And the query is

query HomePageTournaments {
    tournaments {
        id
        first_prize {
            amount
            currency
        }
        second_prize {
            amount
            currency
        }
        third_prize {
            amount
            currency
        }
        fourth_prize {
            amount
            currency
        }
    }
}

The generated Dart class has the following fields:

  final String id;

  final Query$HomePageTournaments$tournaments$first_prize? first_prize;

  final Query$HomePageTournaments$tournaments$second_prize? second_prize;

  final Query$HomePageTournaments$tournaments$third_prize? third_prize;

  final Query$HomePageTournaments$tournaments$fourth_prize? fourth_prize;

While what's desired is

final String id;
Query$HomePageTournaments$tournaments$Prize? firstPrize;
Query$HomePageTournaments$tournaments$Prize? secondPrize;
Query$HomePageTournaments$tournaments$Prize? thridPrize;
Query$HomePageTournaments$tournaments$Prize? forthPrize;

In other words, the generated classes count should be the same as the types count in the schema. Query$HomePageTournaments$tournaments$first_prize and Query$HomePageTournaments$tournaments$second_prize are the same thing.

Am I missing something or this is by design? Thanks in advance :)

github-actions[bot] commented 7 months ago

👋 @SharbelOkzan Thank you for raising an issue. I will investigate the issue and get back to you as soon as possible. Please make sure you have provided enough context.

This library is created and maintained by me, @budde377. Please consider supporting my work and ensure our survival by donating here.

budde377 commented 7 months ago

Thanks for raising this @SharbelOkzan. This is by design the subclasses are not optimised based on the type they are on or the field they select. If you want a single type for each of these, you can define a fragment


fragment Prize on Prize {
  amount
  currency
}

And then spread this in the sub selections

first_price { ... Prize }
...

This will generate a common dart type for each prize.

SharbelOkzan commented 7 months ago

That makes sense.

And thanks for the quick response! Truly appreciate that. Closing as completed.