Kotlin client duplicate classes from codegen

Hello!

I’m currently working on an instant messaging Android app using GraphQL, which is using Apollo Kotlin client (v3).
I face a situation where the generated code contains duplicates of a single class defined in a graph scheme.
For exemple, I have this subscription

subscription events($token: String!) {
	events(token: $token) {
		data {
			... on MyEvent {
				uid
				user {
					[...]
				}
			}
			... on OtherEvent {
				uid
				user {
					[...]
				}
			}
			[other events with the same user node]

When building my module, I end up with multiple generated User class:

public data class EventsSubscription(
  public val token: String,
) : Subscription<EventsSubscription.Data> {
  [...]
  public data class User(...)
  public data class User1(...)
  public data class User2(...)
  public data class User3(...)
  [...]

user nodes in the subscription have the same class from the GraphQL schema
How can I indicate to Apollo to generate only one class/interface for my user class?
Using responseBased doesn’t resolve this issue.

Hi!

This is because the generated code corresponds to the operations rather than the schema (I recommend a blog post by Martin Bonnin about this!).

However you can still reuse classes by using Fragments, for instance:

subscription events($token: String!) {
	events(token: $token) {
		data {
			... on MyEvent {
				uid
				...userFields
			}
			... on OtherEvent {
				uid
				...userFields
			}
			[other events with the same user node]
}

fragment userFields {
	user {
		[...]
	}
}

This should produce a val userFields: UserFields with UserFields being a re-used type.

1 Like