Docs
Launch GraphOS Studio

Enforcing non-nullability

Using the @nonnull directive


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

This is typically the case for relay connections:

type FilmConnection {
# films is nullable here
films: [Film]
}

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

query AllFilms {
allFilms @nonnull {
films @nonnull {
title @nonnull
}
}
}

Will generate the following models:

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

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

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

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

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

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

# Make the 'film' field always non-nullable
extend type FilmConnection @nonnull(fields: "films")
Previous
Uploading files
Next
Using aliases
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company