Example #1
0
    def __render_operation(self, parsed_query: ParsedQuery, buffer: CodeChunk,
                           parsed_op: ParsedOperation):
        buffer.write('@dataclass_json')
        buffer.write('@dataclass')
        with buffer.write_block(f'class {parsed_op.name}:'):
            buffer.write('__QUERY__ = """')
            buffer.write(parsed_query.query)
            buffer.write('"""')
            buffer.write('')

            # Render children
            for child_object in parsed_op.children:
                self.__render_object(parsed_query, buffer, child_object)

            # operation fields
            buffer.write('')
            buffer.write(f'data: {parsed_op.name}Data = None')
            buffer.write('errors: Any = None')
            buffer.write('')

            # Execution functions
            if parsed_op.variables:
                vars_args = ', '.join([
                    self.__render_variable_definition(var)
                    for var in parsed_op.variables
                ]) + ','
                variables_dict = '{' + ', '.join(
                    f'"{var.name}": {var.name}'
                    for var in parsed_op.variables) + '}'
            else:
                vars_args = ''
                variables_dict = 'None'

            buffer.write('@classmethod')
            with buffer.write_block(
                    f'def execute(cls, {vars_args} on_before_callback: Callable[[Mapping[str, str], Mapping[str, str]], None] = None):'
            ):
                buffer.write(f'client = Client(\'{self.config.endpoint}\')')
                buffer.write(f'variables = {variables_dict}')
                buffer.write(
                    'response_text = client.call(cls.__QUERY__, variables=variables, on_before_callback=on_before_callback)'
                )
                buffer.write('return cls.from_json(response_text)')

            buffer.write('')

            buffer.write('@classmethod')
            with buffer.write_block(
                    f'async def execute_async(cls, {vars_args} on_before_callback: Callable[[Mapping[str, str], Mapping[str, str]], None] = None):'
            ):
                buffer.write(
                    f'client = AsyncIOClient(\'{self.config.endpoint}\')')
                buffer.write(f'variables = {variables_dict}')
                buffer.write(
                    f'response_text = await client.call(cls.__QUERY__, variables=variables, on_before_callback=on_before_callback)'
                )
                buffer.write(f'return cls.from_json(response_text)')

            buffer.write('')
            buffer.write('')
Example #2
0
    def __render_enum_field(buffer: CodeChunk):
        with buffer.write_block('def enum_field(enum_type):'):
            with buffer.write_block('def encode_enum(value):'):
                buffer.write('return value.value')
            buffer.write('')
            with buffer.write_block('def decode_enum(t, value):'):
                buffer.write('return t(value)')

            buffer.write('')
            buffer.write("return field(metadata={'dataclasses_json': {'encoder': encode_enum, 'decoder': partial(decode_enum, enum_type)}})")
            buffer.write('')
Example #3
0
    def __render_enum_field(buffer: CodeChunk):
        with buffer.write_block('def enum_field(enum_type):'):
            with buffer.write_block('def encode_enum(value):'):
                buffer.write('return value.value')
            buffer.write('')
            with buffer.write_block('def decode_enum(t, value):'):
                buffer.write('return t(value)')

            buffer.write('')
            buffer.write(
                "return field(metadata={'dataclasses_json': {'encoder': encode_enum, 'decoder': partial(decode_enum, enum_type)}})"
            )
            buffer.write('')
Example #4
0
    def __render_operation(self, parsed_query: ParsedQuery, buffer: CodeChunk, parsed_op: ParsedOperation):
        buffer.write('@dataclass_json')
        buffer.write('@dataclass')
        with buffer.write_block(f'class {parsed_op.name}:'):
            buffer.write('__QUERY__ = """')
            buffer.write(parsed_query.query)
            buffer.write('"""')
            buffer.write('')

            # Render children
            for child_object in parsed_op.children:
                self.__render_object(parsed_query, buffer, child_object)

            # operation fields
            buffer.write('')
            buffer.write(f'data: {parsed_op.name}Data = None')
            buffer.write('errors: Any = None')
            buffer.write('')

            # Execution functions
            if parsed_op.variables:
                vars_args = ', '.join([self.__render_variable_definition(var) for var in parsed_op.variables]) + ','
                variables_dict = '{' + ', '.join(f'"{var.name}": {var.name}' for var in parsed_op.variables) + '}'
            else:
                vars_args = ''
                variables_dict = 'None'

            buffer.write('@classmethod')
            with buffer.write_block(f'def execute(cls, {vars_args} on_before_callback: Callable[[Mapping[str, str], Mapping[str, str]], None] = None):'):
                buffer.write(f'client = Client(\'{self.config.endpoint}\')')
                buffer.write(f'variables = {variables_dict}')
                buffer.write('response_text = client.call(cls.__QUERY__, variables=variables, on_before_callback=on_before_callback)')
                buffer.write('return cls.from_json(response_text)')

            buffer.write('')

            buffer.write('@classmethod')
            with buffer.write_block(f'async def execute_async(cls, {vars_args} on_before_callback: Callable[[Mapping[str, str], Mapping[str, str]], None] = None):'):
                buffer.write(f'client = AsyncIOClient(\'{self.config.endpoint}\')')
                buffer.write(f'variables = {variables_dict}')
                buffer.write(f'response_text = await client.call(cls.__QUERY__, variables=variables, on_before_callback=on_before_callback)')
                buffer.write(f'return cls.from_json(response_text)')

            buffer.write('')
            buffer.write('')
Example #5
0
    def __render_enum(buffer: CodeChunk, enum: ParsedEnum):
        with buffer.write_block(f'class {enum.name}(Enum):'):
            for value_name, value in enum.values.items():
                if isinstance(value, str):
                    value = f"'{value}'"

                buffer.write(f'{value_name} = {value}')

        buffer.write('')
Example #6
0
    def __render_enum(buffer: CodeChunk, enum: ParsedEnum):
        with buffer.write_block(f'class {enum.name}(Enum):'):
            for value_name, value in enum.values.items():
                if isinstance(value, str):
                    value = f"'{value}'"

                buffer.write(f'{value_name} = {value}')

        buffer.write('')
Example #7
0
def test_codegen_write_block(module_compiler):
    gen = CodeChunk()
    with gen.write_block('def {name}(a, b):', name='sum'):
        gen.write('return a + b')

    code = str(gen)

    m = module_compiler(code)
    assert m.sum(2, 3) == 5
Example #8
0
def test_codegen_write_block(module_compiler):
    gen = CodeChunk()
    with gen.write_block('def {name}(a, b):', name='sum'):
        gen.write('return a + b')

    code = str(gen)

    m = module_compiler(code)
    assert m.sum(2, 3) == 5
Example #9
0
    def __render_object(self, parsed_query: ParsedQuery, buffer: CodeChunk, obj: ParsedObject):
        class_parents = '' if not obj.parents else f'({", ".join(obj.parents)})'

        buffer.write('@dataclass_json')
        buffer.write('@dataclass')
        with buffer.write_block(f'class {obj.name}{class_parents}:'):
            # render child objects
            for child_object in obj.children:
                self.__render_object(parsed_query, buffer, child_object)

            # render fields
            sorted_fields = sorted(obj.fields, key=lambda f: 1 if f.nullable else 0)
            for field in sorted_fields:
                self.__render_field(parsed_query, buffer, field)

            # pass if not children or fields
            if not (obj.children or obj.fields):
                buffer.write('pass')

        buffer.write('')
Example #10
0
    def __render_object(self, parsed_query: ParsedQuery, buffer: CodeChunk,
                        obj: ParsedObject):
        class_parents = '' if not obj.parents else f'({", ".join(obj.parents)})'

        buffer.write('@dataclass_json')
        buffer.write('@dataclass')
        with buffer.write_block(f'class {obj.name}{class_parents}:'):
            # render child objects
            for child_object in obj.children:
                self.__render_object(parsed_query, buffer, child_object)

            # render fields
            sorted_fields = sorted(obj.fields,
                                   key=lambda f: 1 if f.nullable else 0)
            for field in sorted_fields:
                self.__render_field(parsed_query, buffer, field)

            # pass if not children or fields
            if not (obj.children or obj.fields):
                buffer.write('pass')

        buffer.write('')