Setting up mutations is as easy as queries, following a very similar process.
All GraphQL mutations start from a root type called Mutation.
This type is auto generated in the file app/graphql/types/mutation_type.rb
:
Types::MutationType = GraphQL::ObjectType.define do
name 'Mutation'
# TODO: Remove me
field :testField, types.String do
description "An example field added by the generator"
resolve ->(obj, args, ctx) {
"Hello World!"
}
end
end
This type is a placeholder for all GraphQL mutations.
To prevent any error when you first start your GraphQL project, it is generated with a dummy testField
field.
You will be able to remove it as soon as you add your own mutation below.
The mutation type is automatically exposed in your schema:
GraphqlTutorialSchema = GraphQL::Schema.define do
query(Types::QueryType)
mutation(Types::MutationType)
end
Now add a resolver for createLink
.
For this purpose, you’ll use GraphQL::Function, as mentioned earlier.
To test, just restart the server again and use the new mutation with GraphiQL:
It’s a good practice in Ruby to unit test your resolver objects.
Here is an example of Resolvers::CreateLink
test:
require 'test_helper'
class Resolvers::CreateLinkTest < ActiveSupport::TestCase
def perform(args = {})
Resolvers::CreateLink.new.call(nil, args, {})
end
test 'creating new link' do
link = perform(
url: 'http://example.com',
description: 'description',
)
assert link.persisted?
assert_equal link.description, 'description'
assert_equal link.url, 'http://example.com'
end
end