def gets_named_operation():
     doc = parse("""
         query TestQ { field }
         mutation TestM { field }
         subscription TestS { field }
         """)
     assert get_operation_ast(doc, "TestQ") == doc.definitions[0]
     assert get_operation_ast(doc, "TestM") == doc.definitions[1]
     assert get_operation_ast(doc, "TestS") == doc.definitions[2]
 def does_not_get_misnamed_operation():
     doc = parse("""
         query TestQ { field }
         mutation TestM { field }
         subscription TestS { field }
         """)
     assert get_operation_ast(doc, "Unknown") is None
 def does_not_get_ambiguous_named_operation():
     doc = parse("""
         query TestQ { field }
         mutation TestM { field }
         subscription TestS { field }
         """)
     assert get_operation_ast(doc) is None
 def does_not_get_ambiguous_unnamed_operation():
     doc = parse("""
         { field }
         mutation Test { field }
         subscription TestSub { field }
         """)
     assert get_operation_ast(doc) is None
Пример #5
0
    async def _ws_on_start(
        self,
        data: Any,
        operation_id: str,
        websocket: WebSocket,
        subscriptions: Dict[str, AsyncGenerator],
    ):
        query = data["query"]
        variable_values = data.get("variables")
        operation_name = data.get("operationName")
        context_value = await self._get_context_value(websocket)
        errors: List[GraphQLError] = []
        operation: Optional[OperationDefinitionNode] = None
        document: Optional[DocumentNode] = None

        try:
            document = parse(query)
            operation = get_operation_ast(document, operation_name)
            errors = validate(self.schema.graphql_schema, document)
        except GraphQLError as e:
            errors = [e]

        if not errors:
            if operation and operation.operation == OperationType.SUBSCRIPTION:
                errors = await self._start_subscription(
                    websocket,
                    operation_id,
                    subscriptions,
                    document,
                    context_value,
                    variable_values,
                    operation_name,
                )
            else:
                errors = await self._handle_query_over_ws(
                    websocket,
                    operation_id,
                    subscriptions,
                    document,
                    context_value,
                    variable_values,
                    operation_name,
                )

        if errors:
            await websocket.send_json({
                "type":
                GQL_ERROR,
                "id":
                operation_id,
                "payload":
                self.error_formatter(errors[0]),
            })
Пример #6
0
def get_response(
    schema: GraphQLSchema,
    params: GraphQLParams,
    catch_exc: Type[BaseException],
    allow_only_query: bool = False,
    run_sync: bool = True,
    validation_rules: Optional[Collection[Type[ASTValidationRule]]] = None,
    max_errors: Optional[int] = None,
    **kwargs,
) -> Optional[AwaitableOrValue[ExecutionResult]]:
    """Get an individual execution result as response, with option to catch errors.

    This will validate the schema (if the schema is used for the first time),
    parse the query, check if this is a query if allow_only_query is set to True,
    validate the query (optionally with additional validation rules and limiting
    the number of errors), execute the request (asynchronously if run_sync is not
    set to True), and return the ExecutionResult. You can also catch all errors that
    belong to an exception class specified by catch_exc.
    """
    # noinspection PyBroadException
    try:
        if not params.query:
            raise HttpQueryError(400, "Must provide query string.")

        schema_validation_errors = validate_schema(schema)
        if schema_validation_errors:
            return ExecutionResult(data=None, errors=schema_validation_errors)

        try:
            document = parse(params.query)
        except GraphQLError as e:
            return ExecutionResult(data=None, errors=[e])
        except Exception as e:
            e = GraphQLError(str(e), original_error=e)
            return ExecutionResult(data=None, errors=[e])

        if allow_only_query:
            operation_ast = get_operation_ast(document, params.operation_name)
            if operation_ast:
                operation = operation_ast.operation.value
                if operation != OperationType.QUERY.value:
                    raise HttpQueryError(
                        405,
                        f"Can only perform a {operation} operation"
                        " from a POST request.",
                        headers={"Allow": "POST"},
                    )

        validation_errors = validate(schema,
                                     document,
                                     rules=validation_rules,
                                     max_errors=max_errors)
        if validation_errors:
            return ExecutionResult(data=None, errors=validation_errors)

        execution_result = execute(
            schema,
            document,
            variable_values=params.variables,
            operation_name=params.operation_name,
            is_awaitable=assume_not_awaitable if run_sync else None,
            **kwargs,
        )

    except catch_exc:
        return None

    return execution_result
 def gets_an_operation_from_a_document_with_named_op_mutation():
     doc = parse("mutation Test { field }")
     assert get_operation_ast(doc) == doc.definitions[0]
 def gets_an_operation_from_a_simple_document():
     doc = parse("{ field }")
     assert get_operation_ast(doc) == doc.definitions[0]
 def does_not_get_missing_operation():
     doc = parse("type Foo { field: String }")
     assert get_operation_ast(doc) is None
Пример #10
0
 def gets_an_operation_from_a_document_with_named_op_subscription():
     doc = parse('subscription Test { field }')
     assert get_operation_ast(doc) == doc.definitions[0]