Skip to content

Commit 2b5f2a7

Browse files
authored
Merge pull request #926 from Netflix/feature/typename-for-interface-fields
Add __typename to projection interface fields
2 parents 927debc + 02795b8 commit 2b5f2a7

2 files changed

Lines changed: 50 additions & 0 deletions

File tree

graphql-dgs-codegen-core/src/main/kotlin/com/netflix/graphql/dgs/codegen/generators/java/ClientApiGenerator.kt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -807,6 +807,16 @@ class ClientApiGenerator(
807807
val javaType = subProjection.first
808808
val codeGenResult = subProjection.second
809809

810+
// Automatically include __typename when the field type is interface to maintain parity with fragment projections
811+
if (type is InterfaceTypeDefinition) {
812+
javaType.addInitializerBlock(
813+
CodeBlock
814+
.builder()
815+
.addStatement("getFields().put(\$S, null)", TypeNameMetaFieldDef.name)
816+
.build(),
817+
)
818+
}
819+
810820
val javaFile = JavaFile.builder(getPackageName(), javaType.build()).build()
811821
return CodeGenResult(clientProjections = listOf(javaFile)).merge(codeGenResult)
812822
}

graphql-dgs-codegen-core/src/test/kotlin/com/netflix/graphql/dgs/codegen/clientapi/ClientApiGenProjectionTest.kt

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,46 @@ class ClientApiGenProjectionTest {
583583
)
584584
}
585585

586+
@Test
587+
fun testInterfaceProjectionIncludesTypenameAutomatically() {
588+
val schema =
589+
"""
590+
type Query {
591+
account: Account
592+
}
593+
594+
type Account {
595+
subscriber: Subscriber
596+
}
597+
598+
interface Subscriber {
599+
id: ID
600+
}
601+
602+
type PremiumSubscriber implements Subscriber {
603+
id: ID
604+
tier: String
605+
}
606+
607+
type BasicSubscriber implements Subscriber {
608+
id: ID
609+
}
610+
""".trimIndent()
611+
612+
val codeGenResult =
613+
CodeGen(
614+
CodeGenConfig(
615+
schemas = setOf(schema),
616+
packageName = BASE_PACKAGE_NAME,
617+
generateClientApi = true,
618+
),
619+
).generate()
620+
621+
val subscriberProjection = codeGenResult.clientProjections.first { it.typeSpec().name() == "SubscriberProjection" }
622+
assertThat(subscriberProjection.typeSpec().initializerBlock().toString()).contains("__typename")
623+
assertCompilesJava(codeGenResult)
624+
}
625+
586626
@Test
587627
fun testScalarsDontGenerateProjections() {
588628
val schema =

0 commit comments

Comments
 (0)