skillbox/server/api/graphene_wagtail.py

61 lines
2.2 KiB
Python

# mysite/api/graphene_wagtail.py
# Taken from https://github.com/patrick91/wagtail-ql/blob/master/backend/graphene_utils/converter.py and slightly adjusted
from graphene.types import Scalar
from graphene_django.converter import convert_django_field
from wagtail.core.fields import StreamField
from wagtail.images.models import Image
from assignments.models import Assignment
class GenericStreamFieldType(Scalar):
@staticmethod
def serialize(stream_value):
stream_data = stream_value.stream_data
for d in stream_data:
if isinstance(d, dict):
_type = d['type']
if _type == 'image_block':
_value = d['value']
value = {
# 'value': _value,
# 'id': d['id'],
'path': Image.objects.get(id=_value).file.url
}
d['value'] = value
if _type == 'assignment':
_value = d['value']
assignment = Assignment.objects.get(pk=_value['assignment_id'])
value = {
'title' : assignment.title,
'assignment': assignment.assignment
}
d['value'] = value
# value = dict(d['value'])
# if 'document' in value:
# value['document'] = Document.objects.get(id=value['document']).file.url
# if 'image' in value:
# value['image'] = Image.objects.get(id=value['image']).file.url
# else:
# _type = d[0]
# value = dict(d[1])
# if 'document' in value:
# value['document'] = value['document'].file.url
# if 'image' in value:
# value['image'] = value['image'].file.url
return stream_data
# by_api = stream_value.stream_block.get_api_representation(stream_value)
# return by_api
@convert_django_field.register(StreamField)
def convert_stream_field(field, registry=None):
return GenericStreamFieldType(description=field.help_text, required=not field.null)