In this article, I would like to focus on adding GraphQL mutations. We will be working on the test application we created previously in this article. It might be helpful for you to know the structure, models, and types we are using so I encourage you to take a look.
We will add
To add your first mutation you have to do three things:
- you have to add
BaseMutation. The simplest way to do so is to add
app/graphql/mutations/base_mutation.rbfile with this content
- The second thing is to add a file with mutation
As you can see, in mutation you have to define arguments that can be passed to the mutation. You have to specify the name, type and decide if the argument is required or not.
Another ingredient is the result type which will be returned after the mutation is complete.
The third necessity is the
resolve method. It executes the action we want to perform. In our case, it is finding the specific author and creating a new book for him/her.
You might have noticed that I created a directory
books in which I added
create_mutation.rb. You don’t have to do this, but I find it easier to group mutations for a specific resource in one directory. Thanks to that I know where to look when there are many
any_other_start_of_mutation_ files in the project.
- the last thing will be adding the mutation to
When we have all of those files in place we can execute the mutation:
And when we query about the author we can see this result:
Unfortunately, we made a typo in the title. It should be “Tripwire” instead of “Tipwire”. We need an endpoint for updating the book.
Because we already have
BaseMutation we can add
Don’t forget to add
field :update_book, mutation: Mutations::Books::UpdateBook to
app/graphql/types/mutation_type.rb! Now we can fix our typo:
The last thing we need is the possibility to remove a book.
We will do this exactly the same way as in the previous examples. We create mutation
and we also should add another line to
app/graphql/types/mutation_type.rb and the final version of this file looks like this:
And now we are able to remove a book:
We created our first GraphQL mutations for most common actions that change the state of the object. There are still many things to add before we can expose our API to the clients. The next artifact to add is something that we neglected a little in this and the previous article. That being said, in the next episode, we will add specs for our queries and mutations.