Docs
Launch GraphOS Studio

Fragments in Apollo Kotlin


Note: This article describes the behavior of when using the default operationBased codegen in . For the responseBased codegen, see this page.

supports both forms of GraphQL fragments:

Named fragments

Take a look at the following definitions:

Launch.graphql
# Declaration of named fragment
fragment launchFragment on Launch {
id
site
mission {
name
}
}
query LaunchDetails($id:ID!) {
launch(id: $id) {
# Usage of named fragment
...launchFragment
}
}

Based on the fragment definition, generates the following LaunchFragment class that you can reuse in different queries:

LaunchFragment.kt
data class LaunchFragment(
val id: String,
val site: String?,
val mission: Mission?
)

Generated models for that use this have a .launchFragment property for accessing the 's :

println("Mission site: ${launch.launchFragment?.site}")

The launchFragment property is null if the returned object is not a Launch.

You can reuse the in any number of :

Launch.graphql
# ...previous definitions...
query LaunchList {
launches {
launches {
...launchFragment
}
}
}

You can even use a in that are defined in a different .graphql file from the itself. This is because codegen merges all .graphql files in to a single file before generating models.

Inline fragments

Take a look at this definition that uses two inline :

HeroQuery.graphql
query HeroForEpisode($ep: Episode!) {
hero(episode: $ep) {
name
... on Droid {
primaryFunction
}
... on Human {
height
}
}
}

For this , generates a Hero class that contains OnDroid and OnHuman nested classes. Hero also includes onDroid and onHuman that enable you to access fields that are specific to Droid and Human:

println("Droid primaryFunction: ${hero.onDroid?.primaryFunction}")
println("Human height: ${hero.onHuman?.height}")

These on<ShapeName> (onDroid and onHuman) are null if the returned object is not the corresponding type.

Previous
Custom scalars
Next
@defer support (experimental)
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company