3

How can I distinguish in java graphQL if a parameter was explicitly set to null, or if it was not provided at all?

The use case that I try to achieve is the following: I have a mutation like this

updateUser(id:Int!, changes:UserChanges!)

#where UserChanges is defined as:
type UserChanges {
    login:String
    email:String
    #etc

}

The idea here is that the user provides only the fields that he wants to change (like react setState for example). So if email is ommited, I want to leave it unchanged.

But what if he/she wants to explicitly set email to null? Is there any way figure this out from my resolver method and act accordingly?

(I use graphql-java-tools library)

2 Answers 2

4

I found the answer. In case somebody needs it: An instance of graphql.schema.DataFetchingEnvironment is available to every resolver method.

This provides methods like getArguments(), hasArgument() etc. Using those methods, we can find out if an argument was an explicit set to null, or if it was not provided at all.

Sign up to request clarification or add additional context in comments.

Comments

0

Looks like deserialization from query/variables is handled by fasterxml Jackson, and that's proper place to deal with the issue, otherwise it becomes too complex: check every field? nested?

So: UserChanges.java should look like this:

class UserChanges {
// SHOULD NOT HAVE ALL ARGUMENT CONSTRUCTOR!
 Optional<String> login;
 Optional<String> email;
 ... getters & setters
}

in this case deserializer will use setters, ONLY FOR PROVIDED FIELDS! And {"login":null} will become:

UserChanges.login = Optional.empty
UserChanges.email = null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.