Setting up Mutations

A mutation is something that “mutates” or changes the data in the server. In DB terms, if we need to change the data in a table using graphql we need mutations — be it an INSERT, UPDATE or DELETE. Only SELECTs are covered with a Query.

So to add a new speaker to the database we need a mutation.

Graphql Mutations

In the GraphQL language, a mutation is of the form

mutation AddSpeaker($name:String, $talkTitle:String) {
  createSpeaker(name: $name, talkTitle:$talkTitle) {
    success
    errors
  }
}

A set of “query” variables needs to be supplied to the GraphQL endpoint. Say for example,

{
  "name": "John Doe",
  "talkTitle": "Introduction to GraphQL in Ruby"
}

Read more about GraphQL mutations and its syntax in the specifications — https://graphql.org/learn/queries/#mutations.

For our little server to accept mutations, we need to make some changes and add more files for defining mutations. Lets see how, step-by-step.

Adding a Mutation root type

A mutation root MutationType has to be created and it should then be added to our Schema, like the QueryType that was added in the last post.

require 'graphql'
require_relative 'mutations/create_speaker'
class MutationType < GraphQL::Schema::Object
description "The mutation root of this schema"
field :createSpeaker, mutation: Mutations::CreateSpeaker
end
view raw mutation.rb hosted with ❤ by GitHub
require 'graphql'
require_relative 'query'
require_relative 'mutation'
class ConferenceAppSchema < GraphQL::Schema
query QueryType
mutation MutationType
end
view raw schema.rb hosted with ❤ by GitHub
Get notified on engineering articles like this

Follow us on twitter @neumeralhq