diff --git a/graphql-dgs-codegen-core/src/main/kotlin/com/netflix/graphql/dgs/codegen/generators/java/ClientApiGenerator.kt b/graphql-dgs-codegen-core/src/main/kotlin/com/netflix/graphql/dgs/codegen/generators/java/ClientApiGenerator.kt index 15373de6..f6b17bb1 100644 --- a/graphql-dgs-codegen-core/src/main/kotlin/com/netflix/graphql/dgs/codegen/generators/java/ClientApiGenerator.kt +++ b/graphql-dgs-codegen-core/src/main/kotlin/com/netflix/graphql/dgs/codegen/generators/java/ClientApiGenerator.kt @@ -807,6 +807,16 @@ class ClientApiGenerator( val javaType = subProjection.first val codeGenResult = subProjection.second + // Automatically include __typename when the field type is interface to maintain parity with fragment projections + if (type is InterfaceTypeDefinition) { + javaType.addInitializerBlock( + CodeBlock + .builder() + .addStatement("getFields().put(\$S, null)", TypeNameMetaFieldDef.name) + .build(), + ) + } + val javaFile = JavaFile.builder(getPackageName(), javaType.build()).build() return CodeGenResult(clientProjections = listOf(javaFile)).merge(codeGenResult) } diff --git a/graphql-dgs-codegen-core/src/test/kotlin/com/netflix/graphql/dgs/codegen/clientapi/ClientApiGenProjectionTest.kt b/graphql-dgs-codegen-core/src/test/kotlin/com/netflix/graphql/dgs/codegen/clientapi/ClientApiGenProjectionTest.kt index da238fe1..549705f9 100644 --- a/graphql-dgs-codegen-core/src/test/kotlin/com/netflix/graphql/dgs/codegen/clientapi/ClientApiGenProjectionTest.kt +++ b/graphql-dgs-codegen-core/src/test/kotlin/com/netflix/graphql/dgs/codegen/clientapi/ClientApiGenProjectionTest.kt @@ -583,6 +583,46 @@ class ClientApiGenProjectionTest { ) } + @Test + fun testInterfaceProjectionIncludesTypenameAutomatically() { + val schema = + """ + type Query { + account: Account + } + + type Account { + subscriber: Subscriber + } + + interface Subscriber { + id: ID + } + + type PremiumSubscriber implements Subscriber { + id: ID + tier: String + } + + type BasicSubscriber implements Subscriber { + id: ID + } + """.trimIndent() + + val codeGenResult = + CodeGen( + CodeGenConfig( + schemas = setOf(schema), + packageName = BASE_PACKAGE_NAME, + generateClientApi = true, + ), + ).generate() + + val subscriberProjection = codeGenResult.clientProjections.first { it.typeSpec().name() == "SubscriberProjection" } + assertThat(subscriberProjection.typeSpec().initializerBlock().toString()).contains("__typename") + assertCompilesJava(codeGenResult) + } + @Test fun testScalarsDontGenerateProjections() { val schema =