Skip to content

Commit

Permalink
Use concrete types for JsonSubType annotations on interfaces if avail…
Browse files Browse the repository at this point in the history
…able. (#683)
  • Loading branch information
srinivasankavitha authored Apr 23, 2024
1 parent 47e98f3 commit d7646cd
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,13 @@ class InterfaceGenerator(private val config: CodeGenConfig, private val document
val implementations = document.getDefinitionsOfType(ObjectTypeDefinition::class.java).asSequence()
.filter { node -> node.implements.any { it.isEqualTo(TypeName(definition.name)) } }
.map { node ->
val nodeName = if (config.generateInterfaces) "I${node.name}" else node.name
typeUtils.findJavaInterfaceName(nodeName, packageName)
typeUtils.findJavaInterfaceName(node.name, packageName)
}
.filterIsInstance<ClassName>()
.toList()

if (implementations.isNotEmpty()) {
// Add JsonSubType annotations only if there are no generated concrete types that implement the interface
if (implementations.isNotEmpty() && config.generateDataTypes) {
javaType.addAnnotation(jsonTypeInfoAnnotation())
javaType.addAnnotation(jsonSubTypeAnnotation(implementations))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2752,6 +2752,42 @@ class CodeGenTest {
assertCompilesJava(dataTypes + interfaces)
}

@Test
fun generatedInterfacesShouldShouldHaveCorrectJsonTypeAnnotations() {
val schema = """
interface Fruit {
seeds: [Seed]
}
type Apple implements Fruit {
seeds: [Seed]
truth: Boolean!
}
type Seed {
shape: String
}
""".trimIndent()

val result = CodeGen(
CodeGenConfig(
schemas = setOf(schema),
packageName = basePackageName,
generateInterfaces = true,
generateIsGetterForPrimitiveBooleanFields = true
)
).generate()

val interfaces = result.javaInterfaces
val dataTypes = result.javaDataTypes

val iFruit = interfaces[2]
assertThat(iFruit.typeSpec.annotations.size).isEqualTo(2)
assertThat(iFruit.typeSpec.annotations[0].toString()).isEqualTo("@com.fasterxml.jackson.annotation.JsonTypeInfo(use = com.fasterxml.jackson.annotation.JsonTypeInfo.Id.NAME, include = com.fasterxml.jackson.annotation.JsonTypeInfo.As.PROPERTY, property = \"__typename\")")
assertThat(iFruit.typeSpec.annotations[1].toString()).isEqualTo("@com.fasterxml.jackson.annotation.JsonSubTypes(@com.fasterxml.jackson.annotation.JsonSubTypes.Type(value = com.netflix.graphql.dgs.codegen.tests.generated.types.Apple.class, name = \"Apple\"))")
assertCompilesJava(dataTypes + interfaces)
}

@Test
fun generateObjectTypeInterfaceWithPrimitiveBooleanShouldUseIsGetter() {
val schema = """
Expand Down

0 comments on commit d7646cd

Please sign in to comment.