PK!   typegql/__init__.pyfrom .core.graph import Graph, InputGraph, GraphInfo, GraphArgument, Connection from .core.schema import Schema from .core.types import ID, DateTime __all__ = ( 'Graph', 'InputGraph', 'GraphInfo', 'GraphArgument', 'Connection', 'Schema', 'ID', 'DateTime' ) PK!typegql/core/__init__.pyPK!i~z'z'typegql/core/graph.pyfrom __future__ import annotations import dataclasses from enum import Enum from typing import get_type_hints, Type, List, Any, TypeVar, Generic import graphql from graphql.pyutils import snake_to_camel from .types import DateTime, ID @dataclasses.dataclass class GraphInfo: name: str = dataclasses.field(default='') required: bool = dataclasses.field(default=False) description: str = dataclasses.field(default='') arguments: List[GraphArgument] = dataclasses.field(default_factory=list) class Graph: _types = { 'ID': graphql.GraphQLID, 'int': graphql.GraphQLInt, 'str': graphql.GraphQLString, 'datetime': DateTime(), 'float': graphql.GraphQLFloat, 'bool': graphql.GraphQLBoolean } def __init__(self, **kwargs): for name, _ in get_type_hints(self.__class__).items(): if name not in kwargs: continue setattr(self, name, kwargs.get(name)) @classmethod def get_fields(cls, graph: Type[Graph], is_mutation=False, camelcase=True): result = dict() meta = getattr(graph, 'Meta', None) for name, _type in get_type_hints(graph).items(): info = getattr(meta, name, GraphInfo()) assert isinstance(info, GraphInfo), f'{graph.__name__} info for `{name}` MUST be of type `GraphInfo`' graph_type = cls.map_type(_type, is_mutation=is_mutation) if not graph_type: continue if cls.is_connection(_type): info.arguments.extend(cls.page_arguments()) if info.required: graph_type = graphql.GraphQLNonNull(graph_type) args = cls.arguments(info) field_name = info.name or name if camelcase: field_name = snake_to_camel(field_name, upper=False) if is_mutation: result[field_name] = graph_type else: result[field_name] = graphql.GraphQLField(graph_type, description=info.description, args=args) return result @classmethod def map_type(cls, _type: Any, is_mutation=False): if isinstance(_type, graphql.GraphQLType): return _type try: type_name = _type.__name__ except AttributeError: type_name = _type._name if not type_name: type_name = _type.__origin__.__name__ if Graph.is_connection(_type): return Connection.get_fields(_type) if Graph.is_enum(_type): if type_name in cls._types: return cls._types.get(type_name) enum_type = graphql.GraphQLEnumType(type_name, _type) cls._types[type_name] = enum_type return enum_type if Graph.is_list(_type): inner = cls.map_type(_type.__args__[0], is_mutation=is_mutation) return graphql.GraphQLList(inner) if Graph.is_graph(_type): return cls.build_object_type(type_name, _type, is_mutation=is_mutation) return cls._types.get(type_name) @staticmethod def is_list(_type: Any) -> bool: try: return issubclass(_type.__origin__, List) except AttributeError: return False @staticmethod def is_enum(_type: Any) -> bool: try: return issubclass(_type, Enum) except TypeError: return False @staticmethod def is_graph(_type: Any) -> bool: try: return issubclass(_type, Graph) except TypeError: return False @staticmethod def is_connection(_type: Any) -> bool: try: return _type.__origin__ is Connection or issubclass(_type.__origin__, Connection) except (TypeError, AttributeError): return False @classmethod def build_object_type(cls, type_name, _type, info: GraphInfo=None, is_mutation=False): if is_mutation: type_name = f'{type_name}Mutation' if type_name in cls._types: return cls._types[type_name] fields = cls.get_fields(_type, is_mutation=is_mutation) if not is_mutation: graph_type = graphql.GraphQLObjectType(type_name, fields=fields) else: graph_type = graphql.GraphQLInputObjectType(type_name, fields=fields) if isinstance(info, GraphInfo): if info.required: graph_type = graphql.GraphQLNonNull(graph_type) cls._types[type_name] = graph_type return graph_type @classmethod def arguments(cls, info: GraphInfo): result: graphql.GraphQLArgumentMap = dict() for arg in getattr(info, 'arguments', []): if not isinstance(arg, GraphArgument): continue _type = cls.map_type(arg.type, is_mutation=arg.is_input) if arg.required: _type = graphql.GraphQLNonNull(_type) result[arg.name] = graphql.GraphQLArgument(_type, description=arg.description) return result @classmethod def page_arguments(cls): return [ GraphArgument[int]('first', description='Retrieve only the first `n` nodes of this connection'), GraphArgument[int]('last', description='Retrieve only the last `n` nodes of this connection'), GraphArgument[str]('before', description='Retrieve nodes for this connection before this cursor'), GraphArgument[str]('after', description='Retrieve nodes for this connection after this cursor') ] T = TypeVar('T') class Node(Graph, Generic[T]): id: ID class Meta: id = GraphInfo(required=True) class Edge(Graph, Generic[T]): node: Node[T] cursor: str class Meta: node = GraphInfo(required=True, description='Scalar representing your data') cursor = GraphInfo(required=True, description='Pagination cursor') class PageInfo(Graph): has_next: bool has_previous: bool start_cursor: str end_cursor: str class Meta: has_next = GraphInfo(required=True, description='When paginating forwards, are there more items?') has_previous = GraphInfo(required=True, description='When paginating backwards, are there more items?') class Connection(Graph, Generic[T]): edges: List[Edge[T]] page_info: PageInfo class Meta: edges = GraphInfo(required=True, description='Connection edges') page_info = GraphInfo(required=True, description='Pagination information') @classmethod def build(cls): if 'Node' not in cls._types: cls._types['Node'] = graphql.GraphQLInterfaceType('Node', super().get_fields(Node)) if 'Edge' not in cls._types: cls._types['Edge'] = graphql.GraphQLInterfaceType('Edge', super().get_fields(Edge)) if 'PageInfo' not in cls._types: cls._types['PageInfo'] = graphql.GraphQLObjectType('PageInfo', super().get_fields(PageInfo)) if 'Connection' not in cls._types: cls._types['Connection'] = graphql.GraphQLInterfaceType('Connection', super().get_fields(Connection)) @classmethod def get_fields(cls, graph: Type[Graph], is_mutation=False, camelcase=True): cls.build() connection_class = graph.__origin__ wrapped = graph.__args__[0] fields = {} meta = getattr(graph, 'Meta', None) for name, _type in get_type_hints(connection_class).items(): info = getattr(meta, name, GraphInfo()) if Graph.is_list(_type) and _type.__args__[0] is Edge[T]: inner = _type.__args__[0] graph_type = graphql.GraphQLList(cls.get_edge_field(inner.__origin__, wrapped, camelcase=camelcase)) else: graph_type = cls.map_type(_type) if info.required: graph_type = graphql.GraphQLNonNull(graph_type) field_name = info.name or name if camelcase: field_name = snake_to_camel(field_name, upper=False) fields[field_name] = graphql.GraphQLField(graph_type, description=info.description) type_name = f'{wrapped.__name__}Connection' return graphql.GraphQLObjectType(type_name, fields=fields, interfaces=(cls._types.get('Connection'),)) @classmethod def get_edge_field(cls, edge_type, inner: Type[T], camelcase=True): fields = dict() meta = getattr(edge_type, 'Meta', None) for name, _type in get_type_hints(edge_type).items(): info = getattr(meta, name, GraphInfo()) if _type is Node[T]: graph_type = cls.get_node_fields(inner) else: graph_type = cls.map_type(_type) if info.required: graph_type = graphql.GraphQLNonNull(graph_type) field_name = info.name or name if camelcase: field_name = snake_to_camel(field_name, upper=False) fields[field_name] = graph_type return graphql.GraphQLNonNull(graphql.GraphQLObjectType( f'{inner.__name__}Edge', fields=fields, interfaces=(cls._types.get('Edge'),) )) @classmethod def get_node_fields(cls, _type: Type[T]): return graphql.GraphQLObjectType( f'{_type.__name__}Node', fields=super().get_fields(_type), interfaces=(cls._types.get('Node'),) ) @dataclasses.dataclass class GraphArgument(Generic[T]): name: str description: str = '' required: bool = False is_input: bool = False @property def type(self): return self.__orig_class__.__args__[0] class InputGraph(Graph): @classmethod def get_fields(cls, graph: Type[InputGraph], is_mutation=False, camelcase=True): return super().get_fields(graph, is_mutation, camelcase) PK!&4a5  typegql/core/schema.pyimport logging from typing import Type, Callable, Any from graphql import GraphQLSchema, GraphQLObjectType, graphql, OperationType, validate_schema from graphql.pyutils import camel_to_snake from typegql.core.graph import Graph logger = logging.getLogger(__name__) class Schema(GraphQLSchema): def __init__(self, query: Type[Graph] = None, mutation: Type[Graph] = None, subscription: Type[Graph] = None, camelcase=True): super().__init__() self.camelcase = camelcase if query: self.query: Callable = query query_fields = query.get_fields(query, camelcase=self.camelcase) query = GraphQLObjectType( 'Query', fields=query_fields, ) if mutation: self.mutation: Callable = mutation mutation_fields = mutation.get_fields(mutation, camelcase=self.camelcase) mutation = GraphQLObjectType( 'Mutation', fields=mutation_fields ) if subscription: self.subscription: Callable = subscription subscription_fields = subscription.get_fields(subscription, camelcase=self.camelcase) subscription = GraphQLObjectType( 'Subscription', fields=subscription_fields ) super().__init__(query, mutation, subscription) errors = validate_schema(self) if errors: raise errors[0] def _field_resolver(self, source, info, **kwargs): field_name = info.field_name if self.camelcase: field_name = camel_to_snake(field_name) if info.operation.operation == OperationType.MUTATION: try: mutation = getattr(source, f'mutate_{field_name}') return mutation(info, **kwargs) except AttributeError: return value = ( source.get(field_name) if isinstance(source, dict) else getattr(source, f'resolve_{field_name}', getattr(source, field_name, None)) ) if callable(value): return value(info, **kwargs) return value async def run(self, query: str, root: Graph = None, operation: str = None, context: Any = None, variables=None, middleware=None): if query.startswith('mutation') and not root: root = self.mutation() elif not root: root = self.query() result = await graphql(self, query, root_value=root, field_resolver=self._field_resolver, operation_name=operation, context_value=context, variable_values=variables, middleware=middleware) return result PK!vvtypegql/core/types.pyimport base64 from datetime import datetime import graphql from graphql.language import ast class DateTime(graphql.GraphQLScalarType): def __init__(self, name='DateTime'): super().__init__( name=name, description='The `DateTime` scalar type represents a DateTime value as specified by ' '[iso8601](https://en.wikipedia.org/wiki/ISO_8601).', serialize=DateTime.serialize, parse_value=DateTime.parse_value, parse_literal=DateTime.parse_literal, ) @staticmethod def serialize(value: datetime): assert isinstance(value, datetime), 'datetime value expected' return value.isoformat() @staticmethod def parse_literal(node): if isinstance(node, ast.StringValueNode): try: return datetime.fromisoformat(node.value) except ValueError: pass @staticmethod def parse_value(value: str): try: return datetime.fromisoformat(value) except ValueError: pass class ID(graphql.GraphQLScalarType): @classmethod def encode(cls, value): if not isinstance(value, str): value = str(value) return base64.b64encode(value.encode()).decode() @classmethod def decode(cls, value): return base64.b64decode(value).decode() PK!H\TTtypegql-0.1.5.dist-info/WHEEL 1 0 нR \I$ơ7.ZON `h6oi14m,b4>4ɛpK>X;baP>PK!HI$1> typegql-0.1.5.dist-info/METADATAXO6= Ti wN(v׭4!TM=8P{v&m}gΘ t7""o}#YDd]5p?ŻeDȧ^\|$P^PMrz#bnT/4/RBĢ+)Y/RHM^,#{ T-xH(>AISmu0j"Ƽt| Ɨޟl d"wYPc eJ7 b!٠`G^p&]3!Jd$k,փ/瓈R(\/bK )88f\ >ҞDA,vO{HخG:fG<ydq|8hLo{{xr4>;=oD/\5a42 µwNN@ >zd,ŴB}М%cD NK>4CBie[f0`hfonK0mDy_5~32Y&%B<'m_s! ˌݶ}[`τU1)B !fR M-xLfKPʸqscC'%ՋZP1ydX.on`ٜ JrW1ΥȉmBCXB%4 NJ)p37\a ``R[}ǝl1+v#A _7j|u48s .k{7hE-jc+kXsOdlZ),A@">PVH+Y@atϯ%~@{^ пny/mDř,I\m z2l0|3MI,Ѝo^MP):yΚ[,9É}]YQx g+$1J3ڪHC}<;󛯿sf)]Mb"bsi6"t0S^p=)+Cбni@.bFIp7$lͨFYDm|:\K{46IN5] dkzZῤ ;e\-T1DS'ZFp1Y I;&KYA|Tp&` @ݰn6S;b L(uY3; E;vZMy{+Lg %yy_z$HynӈT+~xB[)fq¤_4ćz]Fܱ jwl|bwd_u_{>(1{Rl=>㉗4PQ0TxnT=Kβdzpco}V\Vṅs̟_6LB/rgڅy{ ImFԺzFY oc#Qa'pcfΰcfkjsK&UO߼mk/oB^k!MLT5@"ӝpgd"΅& 4țWl1 >Ux^PUU.)JLaPK!H FStypegql-0.1.5.dist-info/RECORDu˒@@| 8E`7"<[P +`0'ʤ*S.(?~&I4IVxaH 9 c{O)$ >q:lk.',O$uM1v+4C{!CK6T 딴-JD)SyGn8>;1#i-(8`_PK!   typegql/__init__.pyPK!<typegql/core/__init__.pyPK!i~z'z'rtypegql/core/graph.pyPK!&4a5  )typegql/core/schema.pyPK!vvi4typegql/core/types.pyPK!H\TT:typegql-0.1.5.dist-info/WHEELPK!HI$1> :typegql-0.1.5.dist-info/METADATAPK!H FS|Atypegql-0.1.5.dist-info/RECORDPK68C