graphene/graphene-sqlalchemy/graphene_sqlalchemy/fields.py

36 lines
1.1 KiB
Python
Raw Normal View History

from sqlalchemy.orm.query import Query
2016-07-18 18:28:12 +03:00
from graphene.relay import ConnectionField
from graphql_relay.connection.arrayconnection import connection_from_list_slice
from .utils import get_query
2016-07-18 18:28:12 +03:00
class SQLAlchemyConnectionField(ConnectionField):
@property
def model(self):
return self.connection._meta.node._meta.model
2016-07-18 18:28:12 +03:00
def get_query(self, context):
return get_query(self.model, context)
2016-07-18 18:28:12 +03:00
def default_resolver(self, root, args, context, info):
return getattr(root, self.source or self.attname, self.get_query(context))
2016-07-18 18:28:12 +03:00
@staticmethod
def connection_resolver(resolver, connection, root, args, context, info):
iterable = resolver(root, args, context, info)
if isinstance(iterable, Query):
_len = iterable.count()
2016-07-18 18:28:12 +03:00
else:
_len = len(iterable)
return connection_from_list_slice(
iterable,
args,
slice_start=0,
list_length=_len,
list_slice_length=_len,
connection_type=connection,
edge_type=connection.Edge,
)