Skip to content

Instantly share code, notes, and snippets.

@thoth-ky
Created February 23, 2019 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thoth-ky/ccfec0ff3cc641c5ef05435ca8108001 to your computer and use it in GitHub Desktop.
Save thoth-ky/ccfec0ff3cc641c5ef05435ca8108001 to your computer and use it in GitHub Desktop.
Example Graphql Mutations
# app/graphql/mutations/create_book.rb
module Mutations
class CreateBook < GraphQL::Schema::RelayClassicMutation
# define return fields (once book is created what can be returned)
field :book, Types::BookType, null: false
# define arguments required to create a book
# you can define a a new Type for inputs so you replace thr following
# lines by something like this:
# argument :bookDetails, Types::BookInputType, required: true
argument :title, String, required: true
argument :author, String, required: true
argument :review, String, required: true
argument :reviewer, String, required: true
# define resolve method
def resolve(args)
begin
book = Book.create(
title: args[:title],
author: args[:author],
review: args[:review],
reviewer: args[:reviewer]
)
{ book: book }
rescue ActiveRecord::RecordInvalid => invalid
GraphQL::ExecutionError.new(
{
errors: invalid.record.errors.full_messages
}.to_json
)
end
end
end
end
# app/graphql/types/mutation_type.rb
module Types
class MutationType < Types::BaseObject
field :createBook, mutation: Mutations::CreateBook
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment