Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decide what root value to use for GraphQL mutations

Tags:

graphql

I'm experimenting with GraphQL and need help understanding how to know what root value to provide when a mutation is about to be performed.

Concrete example: you want to update the username of the currently logged in user. The mutation looks like this:

 mutation TestMutation {
       updateMyUsername(newName: "CoolName") {
                       username }
}

The root object to provide here is the current user. But how do you know this when you receive the mutation without parsing it and seeing its name? No decision is possible based on URL as only one endpoint exists. And parsing the string only to send it further where it will be parsed again sounds wasteful at best.

Is it maybe common practice instead to provide some extra parameters in the URL or request body to give the application more context?

like image 907
kaqqao Avatar asked Apr 21 '16 20:04

kaqqao


People also ask

Can a mutation return nothing GraphQL?

According to this Github issue you cannot return nothing. You can define a return type which is nullable e.g. But I suggest you return the id of the deleted element, because if you want to work with a cached store you have to update the store when the delete mutation has ran successfully.


1 Answers

It's not common to include more data in the URL, but since each mutation is backed by a function, you do not need to parse its name, you can just define this in the function.

Since mutations are always top level, their root object will always be the top level root object. If you need access to a different object, you need to ensure that you've provided enough information to retrieve it

To keep track of the currently logged in user, check out context, one of the initial arguments to run a GraphQL query and provided in each resolution function. Context is very often used to keep track of the logged in user.

Now that you have both a function that defines "changeMyUsername", you have the logged in user, and you have the provided arguments with the new username, you should have everything you need to implement the body of that function.

like image 188
Lee Byron Avatar answered Oct 16 '22 21:10

Lee Byron