Enforcing non-nullability

Using the @nonnull directive


Because GraphQL allows very granular error handling and resolvers may return errors on different fields during execution, many GraphQL schemas expose nullable fields even though these fields should never be null in the absence of errors.

This is typically the case for relay connections:

GraphQL
1type FilmConnection {
2  # films is nullable here
3  films: [Film]
4}

Apollo Kotlin supports the @nonnull client directive. Any field annotated with @nonnull will be made non-null in Kotlin, even if it is nullable in the GraphQL schema. The below query:

Text
1query AllFilms {
2  allFilms @nonnull {
3    films @nonnull {
4      title @nonnull
5    }
6  }
7}

Will generate the following models:

Kotlin
1// All fields are non-nullable
2data class Data(val allFilms: AllFilms)
3data class AllFilms(val films: List<Film?>)
4data class Film(val title: String)

This way, the consuming code doesn't have to use safe calls to access title:

Text
1val title = data.allFilms.films[0]?.title

(Note that individual Films in the list are still nullable, only the field itself is made nonnull.)

Doing this for every query is redundant if you know every FilmConnection will have a nonnull films field. That's why you can also extend your schema.

Create a extensions.graphqls file next to your schema.[graphqls|sdl|json]:

GraphQL
1# Make the 'film' field always non-nullable
2extend type FilmConnection @nonnull(fields: "films")
Feedback

Edit on GitHub

Forums