Created
February 23, 2019 10:51
-
-
Save thoth-ky/ccfec0ff3cc641c5ef05435ca8108001 to your computer and use it in GitHub Desktop.
Example Graphql Mutations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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