Esempio n. 1
0
    def enter_field(self, node, *_):
        name = node.alias.value if node.alias else node.name.value
        graphql_type = self.type_info.get_type()
        python_type, nullable, underlying_graphql_type = self.__scalar_type_to_python(graphql_type)

        parsed_field = ParsedField(
            name=name,
            type=python_type,
            nullable=nullable,
        )

        self.current.fields.append(parsed_field)  # TODO: nullables should go to the end

        if not is_scalar_type(underlying_graphql_type):
            if is_enum_type(underlying_graphql_type):
                enum_type = cast(GraphQLEnumType, self.schema.type_map[underlying_graphql_type.name])
                name = enum_type.name
                if not any(e.name == name for e in self.parsed.enums):  # pylint:disable=not-an-iterable
                    parsed_enum = ParsedEnum(
                        name=enum_type.name,
                        values={name: value.value or name for name, value in enum_type.values.items()}
                    )
                    self.parsed.enums.append(parsed_enum)  # pylint:disable=no-member
            else:
                obj = ParsedObject(
                    name=str(underlying_graphql_type)
                )

                self.current.children.append(obj)
                self.push(obj)

        return node
Esempio n. 2
0
File: main.py Progetto: syfun/gqlcli
def type(ctx, typ: str, kind: str, optional: bool, enum: str):
    """Generate one type"""
    generator = TypeGenerator(kind, optional=optional)
    type_map = ctx.obj['schema'].type_map
    for t in typ:
        if t not in type_map:
            print(f"No '{t}' type.")
            return

        type_ = type_map[t]
        type_def = ''
        if is_enum_type(type_):
            if enum == 'str':
                type_def = generator.str_enum_type(cast(
                    GraphQLEnumType, type_))
            elif enum == 'number':
                type_def = generator.number_enum_type(
                    cast(GraphQLEnumType, type_))
        elif is_object_type(type_):
            type_def = generator.object_type(cast(GraphQLObjectType, type_))
        elif is_interface_type(type_):
            type_def = generator.interface_type(
                cast(GraphQLInterfaceType, type_))
        elif is_input_object_type(type_):
            type_def = generator.input_type(cast(GraphQLInputObjectType,
                                                 type_))

        print(type_def)
Esempio n. 3
0
    def __parse_field(self, name, graphql_type):
        python_type, nullable, underlying_graphql_type = self.__scalar_type_to_python(
            graphql_type
        )

        parsed_field = ParsedField(name=name, type=python_type, nullable=nullable)
        parsed_enum = None

        if not is_scalar_type(underlying_graphql_type):
            if is_enum_type(underlying_graphql_type):
                enum_type = cast(
                    GraphQLEnumType, self.schema.type_map[underlying_graphql_type.name]
                )
                name = enum_type.name
                if not any(e.name == name for e in self.parsed.enums):
                    parsed_enum = ParsedEnum(
                        name=enum_type.name,
                        values={
                            name: value.value or name
                            for name, value in enum_type.values.items()
                        },
                    )
            else:
                return parsed_field, underlying_graphql_type, parsed_enum

        return parsed_field, None, parsed_enum
Esempio n. 4
0
    def enter_field(self, node, *_):
        name = node.alias.value if node.alias else node.name.value
        graphql_type = self.type_info.get_type()
        python_type, nullable, underlying_graphql_type = self.__scalar_type_to_python(graphql_type)

        parsed_field = ParsedField(
            name=name,
            type=python_type,
            nullable=nullable,
        )

        self.current.fields.append(parsed_field)  # TODO: nullables should go to the end

        if not is_scalar_type(underlying_graphql_type):
            if is_enum_type(underlying_graphql_type):
                enum_type = cast(GraphQLEnumType, self.schema.type_map[underlying_graphql_type.name])
                name = enum_type.name
                if not any(e.name == name for e in self.parsed.enums):  # pylint:disable=not-an-iterable
                    parsed_enum = ParsedEnum(
                        name=enum_type.name,
                        values={name: value.value or name for name, value in enum_type.values.items()}
                    )
                    self.parsed.enums.append(parsed_enum)  # pylint:disable=no-member
            else:
                obj = ParsedObject(
                    name=str(underlying_graphql_type)
                )

                self.current.children.append(obj)
                self.push(obj)

        return node
Esempio n. 5
0
File: main.py Progetto: syfun/gqlcli
def all(ctx, kind: str):
    """Generate all schema types"""
    if kind not in ['none', 'dataclass', 'pydantic']:
        print('KIND must be none, dataclass or pydantic')
        return

    generator = TypeGenerator(kind)

    enum_types, interface_types, object_types, input_types = [], [], [], []
    type_map = ctx.obj['schema'].type_map
    for name, type_ in type_map.items():
        if name in ['Query', 'Mutation'] or name.startswith('__'):
            continue
        elif is_enum_type(type_):
            enum_types.append(
                generator.str_enum_type(cast(GraphQLEnumType, type_)))
        elif is_object_type(type_):
            object_types.append(
                generator.object_type(cast(GraphQLObjectType, type_)))
        elif is_interface_type(type_):
            interface_types.append(
                generator.interface_type(cast(GraphQLInterfaceType, type_)))
        elif is_input_object_type(type_):
            input_types.append(
                generator.input_type(cast(GraphQLInputObjectType, type_)))

    type_resolvers = TypeResolverGenerator(type_map).all_type_resolvers()
    imports, body = '', ''

    if enum_types:
        body += '\n'.join(enum_types) + '\n'
    if interface_types:
        body += '\n'.join(interface_types) + '\n'
    if object_types:
        body += '\n'.join(object_types) + '\n'
    if input_types:
        body += '\n'.join(input_types)
    if type_resolvers:
        body += '\n'.join(type_resolvers)

    if kind == 'dataclass':
        imports += 'from dataclasses import dataclass\n'
    if enum_types:
        imports += 'from enum import Enum\n'
    imports += 'from typing import Any, Dict, List, NewType, Optional, Union\n\n'
    imports += 'from gql import enum_type, type_resolver\n'
    if kind == 'pydantic':
        imports += 'from pydantic import BaseModel\n'
    imports += '\n'

    print(imports + body)
Esempio n. 6
0
def map_schema_types(schema, ignore=['Query', 'Mutation']):
    """Iterate over a graphQl schema to get the schema types and its relations

    The process ignores the root types like Query and Mutation and the Scalar types"""
    objects = dict()
    enums = dict()
    for type_name, type_obj in schema.type_map.items():
        # Iterating over all the items of the schema
        # Ignore internal types and root types
        if (type_name[:2] != '__') and (type_name not in ignore):
            # ENUM types
            if is_enum_type(type_obj):
                enums[type_name] = []  # values
            # Graphql Types
            elif is_object_type(type_obj):
                #Create the type obj
                obj = _get_object(objects, type_name)

                # Iterate over all fields of the graphql type
                for field_name, field_obj in type_obj.fields.items():
                    field = get_named_type(
                        field_obj.type)  # Returns a scalar or an object
                    # setting non null
                    nullable = True
                    if contains_non_null_type(field_obj.type):
                        nullable = False

                    if is_scalar_type(field):
                        obj['field'][field_name] = {
                            'type': field.name,
                            'nullable': nullable
                        }
                    elif is_object_type(field):
                        # if it's a list of types, that means that I'm the parent in a one to many relationship
                        list_ = False
                        if contains_list_type(field_obj.type):
                            list_ = True
                        obj['relationship'][field_name] = {
                            'type': field.name,
                            'nullable': nullable,
                            'list': list_
                        }

    return {'objects': objects, 'enums': enums}
    def compare_types(old_type, new_type):
        changes = []
        if old_type.description != new_type.description:
            changes.append(TypeDescriptionChanged(new_type.name, old_type.description, new_type.description))

        if type_kind(old_type) != type_kind(new_type):
            changes.append(TypeKindChanged(new_type, type_kind(old_type), type_kind(new_type)))
        else:
            if is_enum_type(old_type):
                changes += EnumDiff(old_type, new_type).diff()
            elif is_union_type(old_type):
                changes += UnionType(old_type, new_type).diff()
            elif is_input_object_type(old_type):
                changes += InputObjectType(old_type, new_type).diff()
            elif is_object_type(old_type):
                changes += ObjectType(old_type, new_type).diff()
            elif is_interface_type(old_type):
                changes += InterfaceType(old_type, new_type).diff()

        return changes