From 5725c3d4e48e9dea1b725984ea051c985d0b6b19 Mon Sep 17 00:00:00 2001 From: Ramon Wenger Date: Mon, 10 Sep 2018 09:52:38 +0200 Subject: [PATCH] Update content block mutation --- server/book/schema/mutations.py | 49 +++++++++++++++++++++++---------- 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/server/book/schema/mutations.py b/server/book/schema/mutations.py index dd7cc7bb..015a9c93 100644 --- a/server/book/schema/mutations.py +++ b/server/book/schema/mutations.py @@ -95,26 +95,45 @@ class AddContentBlock(relay.ClientIDMutation): class Input: content_block = graphene.Argument(ContentBlockInput) # todo: handle both of these differently, one for a new chapter maybe - parent = graphene.ID() - after = graphene.ID() + parent = graphene.ID() # ID of chapter node; new content block will be inserted at the start of it + after = graphene.ID() # ID of content block node; new content block will be inserted after this content block node new_content_block = graphene.Field(ContentBlockNode) + errors = graphene.List(graphene.String) + + @classmethod + def create_content_block(cls, content_block_data): + title = content_block_data.get('title') + contents = content_block_data.get('contents') + new_contents = handle_content_blocks(contents) + return ContentBlock(title=title, contents=new_contents) @classmethod def mutate_and_get_payload(cls, root, info, **args): - content_block_data = args.get('content_block') - title = content_block_data.get('title') - new_content_block = ContentBlock(title=title) - parent = Chapter.objects.get( - pk=18).specific # atm just "1.1 Lehrbeginn" / todo: dynamic, refactor in above class - parent.add_child(instance=new_content_block) - revision = new_content_block.save_revision() - revision.publish() - contents = content_block_data.get('contents') - new_contents = handle_content_blocks(contents) - new_content_block.contents = json.dumps(new_contents) - new_content_block.save() - return cls(new_content_block=new_content_block) + try: + parent = args.get('parent', None) + after = args.get('after', None) + if after is not None: + new_content_block = cls.create_content_block(content_block_data=args.get('content_block')) + sibling = get_object(ContentBlock, after) + sibling.add_sibling(instance=new_content_block, pos='right') + elif parent is not None: + new_content_block = cls.create_content_block(content_block_data=args.get('content_block')) + parent = get_object(Chapter, parent) + parent.add_child(instance=new_content_block) + else: + raise Exception('Define either a parent or a sibling id') + revision = new_content_block.save_revision() + revision.publish() + new_content_block.save() + return cls(new_content_block=new_content_block) + + except ValidationError as e: + errors = get_errors(e) + except Exception as e: + errors = ['Error: {}'.format(e)] + + return cls(new_content_block=None, errors=errors) class BookMutations(object):