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.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Assume we have an input class for a update mutation on some kind of dog 🐕 enitity, which looks like this.
We always need the
idof the dog in the input to find the corresponding entity. Bothnameanddescriptionare optional and can be set to either someStringornull. But now I have the requirement that it SHOULD NOT be possible thatnameist 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 anullvalue (likenameshould 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?>,descriptioncan be set tonullbut withval name: OptionalInput<String>,nameshould not be able to be set tonulland 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 thevaluefield ofOptionalInputis always nullable!I looked into the
OptionalInputsource code and found the current implementation which looks like so:As you can see the constructor parameter
valueof theDefinedclass is of typeU?. I think this is a design issue which leads to my described issue. The generic parameterUshould 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
Uand the consumer is responsible for deciding whether anOptionalInputcan be set tonullor must have a value.I would love to hear what you think! 😄
Beta Was this translation helpful? Give feedback.
All reactions