Using GraphQL variables in Apollo Kotlin
GraphQL supports passing argument values to your operations with variables. This enables you to write a single query that you can reuse with multiple variable values (this is a recommended best practice).
In GraphQL, non-nullable variables are required, and nullable variables are always optional. Apollo Kotlin uses its own Optional
type to distinguish between present (but maybe nullable) and absent types.
Consider the following GraphQL query with two nullable variables:
query GetTodos($first: Int, $offset: Int) {todos(first: $first, offset: $offset) {idtext}}
Apollo Kotlin generates the following Kotlin code for this query:
class GetTodosQuery(val first: Optional<Int?> = Optional.Absent,val offset: Optional<Int?> = Optional.Absent)
You can then selectively provide or omit variable values like so:
// Omit values for both variablesval query = GetTodosQuery(Optional.Absent, Optional.Absent)// Provide null for both variablesval query = GetTodosQuery(Optional.Present(null), Optional.Present(null))// Send explicit values for both variablesval query = GetTodosQuery(Optional.Present(100), Optional.Present(0))
Using input builders
For both operations and input objects, having to wrap values in an Optional
wrapper can be cumbersome.
For those cases, use generateInputBuilders
:
apollo {service("service") {// ...generateInputBuilders.set(true)}}
If you do, in the case of the GetTodos
query shown above, Apollo Kotlin now generates a Builder
for each operation:
// Omit values for both variablesval query = GetTodosQuery.Builder().build()// Provide null for both variablesval query = GetTodosQuery.Builder().first(null).offset(null).build()// Send explicit values for both variablesval query = GetTodosQuery.Builder().first(100).offset(0).build()