Non-nullable OptionalInput #1218
Replies: 2 comments
-
Hello 👋 |
Beta Was this translation helpful? Give feedback.
-
The validation logic you are looking for can be written yourself but I don't think this would be something we add to the library as you said yourself, it goes against the type system. fun optionalScalarInput(input: OptionalInput<String>): String = when (input) {
is OptionalInput.Undefined -> throw Exception("Sorry, we don't actually like nulls")
is OptionalInput.Defined<String> -> doThingsWithValue(input.value)
} |
Beta Was this translation helpful? Give feedback.
-
Assume we have an input class for a update mutation on some kind of dog 🐕 enitity, which looks like this.
We always need the
id
of the dog in the input to find the corresponding entity. Bothname
anddescription
are optional and can be set to either someString
ornull
. But now I have the requirement that it SHOULD NOT be possible thatname
ist set tonull
. So I want an input to be optional in the request (maybe I just want to update the description but not the name) but this does not mean that it always allowed to be anull
value (likename
should not be allowed to be set tonull
).I would expect this to be configuratble by setting the desired generics of
OptionalInput
, like so:Note that with
val description: OptionalInput<String?>
,description
can be set tonull
but withval name: OptionalInput<String>
,name
should not be able to be set tonull
and I want a validation error message if someone tries to do so in a request. But this is not possible with the current OptionalInput implementation, because thevalue
field ofOptionalInput
is always nullable!I looked into the
OptionalInput
source code and found the current implementation which looks like so:As you can see the constructor parameter
value
of theDefined
class is of typeU?
. I think this is a design issue which leads to my described issue. The generic parameterU
should be responsible for deciding whether the value is nullable or not. Therefore I suggest that the constructor should look like so:Note that value is now of type
U
and the consumer is responsible for deciding whether anOptionalInput
can be set tonull
or must have a value.I would love to hear what you think! 😄
Beta Was this translation helpful? Give feedback.
All reactions