⚠ New Class-Based API ⚠

This describes a new API in v1.8.0. Check the upgrade notes for more info.

Mutation Classes

GraphQL mutations are special fields: instead of reading data or performing calculations, they may modify the application state. For example, mutation fields may:

These actions are called side effects.

Like all GraphQL fields, mutation fields:

GraphQL-Ruby includes two classes to help you write mutations:

Besides those, you can also use the plain field API to write mutation fields.

An additional null helper method is provided on classes inheriting from GraphQL::Schema::Mutation to allow setting the nullability of the mutation. This is not required and defaults to true.

Example mutation class

You should add a base class to your application, for example:

class Mutations::BaseMutation < GraphQL::Schema::RelayClassicMutation

Then extend it for your mutations:

class Mutations::CreateComment < Mutations::BaseMutation
  null true

  argument :body, String, required: true
  argument :post_id, ID, required: true

  field :comment, Types::Comment, null: true
  field :errors, [String], null: false

  def resolve(body:, post_id:)
    post = Post.find(post_id)
    comment = post.comments.build(body: body, author: context[:current_user])
    if comment.save
      # Successful creation, return the created object with no errors
        comment: comment,
        errors: [],
      # Failed save, return the errors to the client
        comment: nil,
        errors: comment.errors.full_messages

The #resolve method should return a hash whose symbols match the field names.

(See Mutation Errors for more information about returning errors.)

Hooking up mutations

Mutations must be attached to the mutation root using the mutation: keyword, for example:

class Types::Mutation < Types::BaseObject
  field :create_comment, mutation: Mutations::CreateComment