Skip to content

Instantly share code, notes, and snippets.

@harigopal
Last active November 6, 2019 19:55
Show Gist options
  • Save harigopal/da0fe5301af5027e84ec0f0f9a5c83dc to your computer and use it in GitHub Desktop.
Save harigopal/da0fe5301af5027e84ec0f0f9a5c83dc to your computer and use it in GitHub Desktop.
Conventions for setting up a GraphQL Server on Rails - Create a comment
# app/graphql/mutations/create_comment.rb
module Mutations
class CreateComment < GraphQL::Schema::Mutation
argument :post_id, ID, required: true
argument :comment, String, required: true
description "Create a comment on a post"
field :id, ID, null: true
field :errors, [String], null: false
def resolve(params)
# Step 1: Create a mutator.
mutator = CreateCommentMutator.new(context, params)
# Step 2: Check if the request is valid?
if mutator.valid?
# Step 3.1: A successful response.
{ id: mutator.create_comment.id, errors: [] }
else
# Step 3.2: A 'handled' failure.
{ id: nil, errors: mutator.errors.full_messages }
end
end
end
end
# app/graphql/types/mutation_type.rb
module Types
class MutationType < Types::BaseObject
field :create_comment, mutation: Mutations::CreateComment, null: false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment