Graphql-ruby mutations

From wikinotes
Revision as of 21:16, 5 September 2021 by Will (talk | contribs) (→‎Basics)

Mutations are graphql fields that trigger side effects.

  • mutations return a hash, that contains all of the fields defined on it.
  • mutations may optionally accept arguments

Basics

Set the root-mutation object on the schema

class MyGraph < GraphQL::Schema
  mutation(MyMutationRoot)
end

Add your mutations as fields on the mutation-root

class MyMutationRoot < GraphQL::Schema::RelayClassicMutation
  field :mymutation,
    mutation: MyMutation  # TODO: needs arg??
end

Define your mutation

class MyMutation < GraphQL::Schema::RelayClassicMutation
  argument :username, String, required: true

  field :message, String, null: true    # returns string, allows null
  field :errors, [String], null, false  # returns list of strings, disallows null

  def resolve(username)
    # do thing that produces side effect
    { message: "Hello #{username}",
      errors: [] }
  end
end