Exemplo n.º 1
0
def execution_to_dict(execution_result):
    result = {}
    if execution_result.invalid:
        result["errors"] = [default_format_error(e) for e in execution_result.errors]
    if execution_result.data:
        result["data"] = execution_result.data

    return result
Exemplo n.º 2
0
    async def dispatch_request(self, request, *args, **kwargs):
        try:
            request_method = request.method.lower()
            data = self.parse_body(request)

            show_graphiql = request_method == "get" and self.should_display_graphiql(
                request
            )
            catch = show_graphiql

            pretty = self.pretty or show_graphiql or request.args.get("pretty")

            if request_method != "options":
                execution_results, all_params = run_http_query(
                    self.schema,
                    request_method,
                    data,
                    query_data=request.args,
                    batch_enabled=self.batch,
                    catch=catch,
                    # Execute options
                    return_promise=self._enable_async,
                    root_value=self.get_root_value(request),
                    context_value=self.get_context(request),
                    middleware=self.get_middleware(request),
                    executor=self.get_executor(request),
                )
                awaited_execution_results = await Promise.all(execution_results)
                result, status_code = encode_execution_results(
                    awaited_execution_results,
                    is_batch=isinstance(data, list),
                    format_error=self.format_error,
                    encode=partial(self.encode, pretty=pretty),
                )

                if show_graphiql:
                    return await self.render_graphiql(
                        params=all_params[0], result=result
                    )

                return HTTPResponse(
                    result, status=status_code, content_type="application/json"
                )

            else:
                return self.process_preflight(request)

        except HttpQueryError as e:
            return HTTPResponse(
                self.encode({"errors": [default_format_error(e)]}),
                status=e.status_code,
                headers=e.headers,
                content_type="application/json",
            )
Exemplo n.º 3
0
    def log_and_format_exception(error):
        """captures the exception catch in graphql_server and log to the stdout
        with the stacktrace included.

        once thats done, call the default_format_error for the  graphql_server
        package

        Arguments:
            error {[type]} -- error catch by the graphql server

        Returns:
            [str] -- constaining the string representation of the error
                     encountered by the graphql endpoint
        """
        if hasattr(error, "original_error") and isinstance(
            error.original_error, Exception
        ):
            logger.error("error in GraphQL view", exc_info=error.original_error)
        return default_format_error(error)
Exemplo n.º 4
0
 def _process_request(self, schema, data):
     try:
         request = http.request.httprequest
         context = self._make_context(schema, data)
         execution_results, all_params = run_http_query(
             schema,
             request.method.lower(),
             data,
             query_data=request.args,
             batch_enabled=False,
             catch=False,
             context=context,
         )
         result, status_code = encode_execution_results(
             execution_results,
             is_batch=isinstance(data, list),
             format_error=default_format_error,
             encode=partial(json_encode, pretty=False),
         )
         headers = dict()
         headers["Content-Type"] = "application/json"
         response = http.request.make_response(result, headers=headers)
         response.status_code = status_code
         if any(er.errors for er in execution_results):
             env = http.request.env
             env.cr.rollback()
             env.clear()
         return response
     except HttpQueryError as e:
         result = json_encode({"errors": [default_format_error(e)]})
         headers = dict(e.headers)
         headers["Content-Type"] = "application/json"
         response = http.request.make_response(result, headers=headers)
         response.status_code = e.status_code
         env = http.request.env
         env.cr.rollback()
         env.clear()
         return response
Exemplo n.º 5
0
def handle_graphql_error(error):
    response = jsonify({'errors': [default_format_error(error)]})
    response.status_code = error.status_code
    response.headers = error.headers
    return response
Exemplo n.º 6
0
    def _format_error(self, request: Request, error: T_error):
        formatted = self.format_error(request, error)

        if formatted is not None:
            return formatted
        return default_format_error(error)
Exemplo n.º 7
0
    async def dispatch_request(self, request, *args, **kwargs):
        """ Sanic view request dispatch.  """
        start_time = time.time()  # TODO this is debug profile

        with ax_model.scoped_session("GQL error -") as db_session:
            try:
                request_method = request.method.lower()
                data = self.parse_body(request)

                show_graphiql = request_method == 'get' and self.should_display_graphiql(
                    request)
                catch = show_graphiql

                pretty = self.pretty or show_graphiql or request.args.get(
                    'pretty')

                user = kwargs['user'] or None

                # auth_header = request.headers['authorization']
                # print(auth_header)

                ax_context = self.get_context(request)
                ax_context.update({'session': db_session})
                ax_context.update({'user': user})

                if request_method != 'options':
                    execution_results, all_params = run_http_query(
                        ax_schema.schema,
                        request_method,
                        data,
                        query_data=request.args,
                        batch_enabled=self.batch,
                        catch=catch,

                        # Execute options
                        return_promise=self._enable_async,
                        root_value=self.get_root_value(request),
                        context_value=ax_context,
                        middleware=self.get_middleware(request),
                        executor=self.get_executor(request),
                    )  # pylint: disable=unused-argument
                    del all_params
                    awaited_execution_results = await Promise.all(
                        execution_results)
                    result, status_code = encode_execution_results(
                        awaited_execution_results,
                        is_batch=isinstance(data, list),
                        format_error=self.format_error,
                        encode=partial(self.encode, pretty=pretty))
                    log_reguest(request, (time.time() - start_time))

                    return HTTPResponse(result,
                                        status=status_code,
                                        content_type='application/json')
                else:
                    log_reguest(request, (time.time() - start_time))
                    return self.process_preflight(request)

            except HttpQueryError as err:
                logger.exception(f'graqlView -> {err}')
                return HTTPResponse(self.encode(
                    {'errors': [default_format_error(err)]}),
                                    status=err.status_code,
                                    headers=err.headers,
                                    content_type='application/json')
            except Exception as err:  # pylint: disable=broad-except
                logger.exception(f'graqlView -> {err}')