Skip to content

Instantly share code, notes, and snippets.

@andela-sjames
Created November 16, 2017 19:11
Show Gist options
  • Save andela-sjames/916ca78010b77126e28221dd561d782d to your computer and use it in GitHub Desktop.
Save andela-sjames/916ca78010b77126e28221dd561d782d to your computer and use it in GitHub Desktop.
class CreateBook(relay.ClientIDMutation):
class Input:
# BookCreateInput class used as argument here.
book = graphene.Argument(BookCreateInput)
new_book = graphene.Field(BookNode)
@classmethod
def mutate_and_get_payload(cls, args, context, info):
book_data = args.get('book') # get the book input from the args
book = Book() # get an instance of the book model here
new_book = update_create_instance(book, book_data) # use custom function to create book
return cls(new_book=new_book) # newly created book instance returned.
class UpdateBook(relay.ClientIDMutation):
class Input:
book = graphene.Argument(BookCreateInput) # get the book input from the args
id = graphene.String(required=True) # get the book id
errors = graphene.List(graphene.String)
updated_book = graphene.Field(BookNode)
@classmethod
def mutate_and_get_payload(cls, args, context, info):
try:
book_instance = get_object(Book, args['id']) # get book by id
if book_instance:
# modify and update book model instance
book_data = args.get('book')
updated_book = update_create_instance(book_instance, book_data)
return cls(updated_book=updated_book)
except ValidationError as e:
# return an error if something wrong happens
return cls(updated_book=None, errors=get_errors(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment