GraphQL Mutations In Ruby On Rails

・3 min read
GraphQL Mutations In Ruby On Rails

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 createBook, updateBook and destroyBook. Here are the GraphQL mutation examples:

createBook

To add your first mutation you have to do three things:

  1. you have to add BaseMutation. The simplest way to do so is to add app/graphql/mutations/base_mutation.rb file with this content
  1. The second thing is to add a file with mutation app/graphql/mutations/books/create_book.rb

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 create_, update_, destroy_, any_other_start_of_mutation_ files in the project.

  1. the last thing will be adding the mutation to app/graphql/types/mutation_type.rb

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.

updateBook

Because we already have BaseMutation we can add UpdateBook in app/graphql/mutations/books/update_book.rb

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.

destroyBook

We will do this exactly the same way as in the previous examples. We create mutation app/graphql/mutations/books/destroy_book.rb

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:

Summary

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.

If you need help with your mutations or Ruby on Rails development, feel free to contact our team!

Related articles