Ejemplo n.º 1
0
def dsl_gql(
    *operations: "DSLOperation", **operations_with_name: "DSLOperation"
) -> DocumentNode:
    r"""Given arguments instances of :class:`DSLOperation`
    containing GraphQL operations,
    generate a Document which can be executed later in a
    gql client or a gql session.

    Similar to the :func:`gql.gql` function but instead of parsing a python
    string to describe the request, we are using operations which have been generated
    dynamically using instances of :class:`DSLField`, generated
    by instances of :class:`DSLType` which themselves originated from
    a :class:`DSLSchema` class.

    :param \*operations: the GraphQL operations
    :type \*operations: DSLOperation (DSLQuery, DSLMutation, DSLSubscription)
    :param \**operations_with_name: the GraphQL operations with an operation name
    :type \**operations_with_name: DSLOperation (DSLQuery, DSLMutation, DSLSubscription)

    :return: a Document which can be later executed or subscribed by a
        :class:`Client <gql.client.Client>`, by an
        :class:`async session <gql.client.AsyncClientSession>` or by a
        :class:`sync session <gql.client.SyncClientSession>`

    :raises TypeError: if an argument is not an instance of :class:`DSLOperation`
    """

    # Concatenate operations without and with name
    all_operations: Tuple["DSLOperation", ...] = (
        *operations,
        *(operation for operation in operations_with_name.values()),
    )

    # Set the operation name
    for name, operation in operations_with_name.items():
        operation.name = name

    # Check the type
    for operation in all_operations:
        if not isinstance(operation, DSLOperation):
            raise TypeError(
                "Operations should be instances of DSLOperation "
                "(DSLQuery, DSLMutation or DSLSubscription).\n"
                f"Received: {type(operation)}."
            )

    return DocumentNode(
        definitions=[
            OperationDefinitionNode(
                operation=OperationType(operation.operation_type),
                selection_set=operation.selection_set,
                variable_definitions=FrozenList(
                    operation.variable_definitions.get_ast_definitions()
                ),
                **({"name": NameNode(value=operation.name)} if operation.name else {}),
            )
            for operation in all_operations
        ]
    )
Ejemplo n.º 2
0
Archivo: dsl.py Proyecto: mousewu/gql
def query(*fields, **kwargs):
    if "operation" not in kwargs:
        kwargs["operation"] = "query"
    return DocumentNode(definitions=[
        OperationDefinitionNode(
            operation=OperationType(kwargs["operation"]),
            selection_set=SelectionSetNode(
                selections=FrozenList(selections(*fields))),
        )
    ])