Define a Create Mutation

Next, we need to tell GraphQL about the parameters that needs to be accepted for creating a new speaker.

Let’s split this into a separate file, that handles this mutation — create_speaker.rb. Instead of inheriting from GraphQL::Schema::Mutation we create a mutation base class Mutations::BaseMutation. Also group all the mutations in mutations folder.

It needs to accept all the fields for a speaker, which we created as strings in the DB. In GraphQL ruby, strings are represented with the String type, as defined in the gem.

Next we need to take these fields and then call speaker.save with the defined input fields in the resolve function.

This returns a hash with success and errors. We need to tell GraphQL about it as well. Note: errors is an array of Strings. We define these as “fields” in the mutation.

Now the CreateSpeaker mutation is complete. It needs to be added to the root mutation — MutationType so that it gets included in the schema.

Restart the server with bundle exec puma.

If you use a client like GraphiQL, you should be able to see the docs in the right sidebar changes and now has a Mutation.

Add a new speaker, with the mutation and the query variables in the client.

Execute the mutation in the GraphiQL client. You should be able to see the response data json, with something like below:

GraphiQL Mutation Execution

The CreateSpeaker mutation has all the fields optional, but the Speaker model validates the presence of the name field. If you try to create a speaker without giving a name field, it will show up in errors return field.

We can avoid this validation at the schema level, by making the required argument mandatory. You just need to change null: false to the respective arguments.

Now the name and talk_title fields are non-nullable fields, and you’ll have to always give these fields when executing the mutation. Read about the type system in the official documentation.

Get notified on engineering articles like this

Follow us on twitter @neumeralhq